<?php if (!defined("BASEPATH")) exit("No direct script access allowed");

class Admin extends MY_Controller {

	function __construct() {
		parent::__construct();
		if(!(Common::isAdmin() or Common::isSuperAdmin()) and $this->uri->segment(2) != "login") {
			$this->session->sess_destroy();
			$this->db->query("commit");
			redirect("admin/login");
		}
		$this->db->cache_off();

		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Cache-Control: no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false );
		header("Pragma: no-cache");

		if(Common::isAdmin()) {
			$this->load->model("usr2ent");
			$this->getUsr2ent = $this->usr2ent->getUsr2ent("u2e_usr_id = '".$this->session->userdata("usrId")."'");
		}

	}

	function getMenu() {
		if(Common::isSuperAdmin()) {
			$arrMenu["ADMIN"] = array(
				array("name" => $this->lang->line("LOGS"), "url" => "admin/logs"),
				array("name" => $this->lang->line("ARTICLES"), "url" => "admin/article"),
				array("name" => $this->lang->line("LANGUAGE"), "url" => "admin/language"),
				array("name" => $this->lang->line("MAIN_DATA"), "url" => "admin/basic_data"),
				array("name" => $this->lang->line("CATEGORIES"), "url" => "admin/category"),
				array("name" => $this->lang->line("EDITING_DATA"), "url" => "admin/data_edit"),
				array("name" => $this->lang->line("MESSAGES"), "url" => "admin/messages"),
			);
		}

		if(Common::isSuperAdmin()) {
			$arrMenu["ADMIN"] += array(
				count($arrMenu["ADMIN"]) => array("name" => $this->lang->line("USERS"), "url" => "admin/user"),
				(count($arrMenu["ADMIN"])+1) =>array("name" => $this->lang->line("NEWSLETTER"), "url" => "admin/newsletter"),
			);
		}

		/* Intezmenyi menupontok */
		if(Common::isAdmin()) {
			$arrMenu["ADMINISTRATION_OF_INSTITUTE"] = array(
				array("name" => $this->lang->line("PROFIL"), "children" => array(
					array("name" => $this->lang->line("CHANGE_PASSWORD"), "url" => "admin/password_change"),
					array("name" => $this->lang->line("MANAGING_ADMINISTRATORS"), "url" => "admin/user"),
					array("name" => $this->lang->line("CONTACT_INFORMATION"), "url" => ""),
				)),
				array("name" => $this->lang->line("MESSAGES"), "children" => array(
					array("name" => $this->lang->line("MY_MESSAGES"), "url" => "admin/messages"),
				)),
				array("name" => $this->lang->line("BILLING_INFORMATION"), "url" => ""),
				((Common::isAdminJog("PAGE_CAT_ART"))?(array("name" => $this->lang->line("ARTICLES"), "url" => "admin/article")):(array())),
				
				((Common::isAdminJog("PAGE_CAT_MAJ") or Common::isAdminJog("PAGE_CAT_SCH") or Common::isAdminJog("COU") or Common::isAdminJog("CITY") or Common::isAdminJog("INS"))?(array("name" => $this->lang->line("EDITING_DATA"), "url" => "admin/data_edit")):(array())),
			);
		}

		echo	"[";
		$ii = 0;

		foreach($arrMenu as $cat => $catData) {
			echo	(($ii)?(","):(""))."{
				label: '".$this->db->escape_str($this->lang->line($cat))."',
				iconCls: 'treenode-no-icon',
				expanded: true,
				children:[
				";

			$jj = 0;
			foreach($catData as $d) {
				if(!empty($d)) {
					if(!isset($d["children"])) {
						echo		(($jj)?(","):(""))."{label: '".$this->db->escape_str(anchor($d["url"], $d["name"], "onclick=\"return false;\" style=\"margin-left: -15px;\" "))."', url: '".(($d["url"])?($d["url"]):(""))."', title: '".$d["name"]."', iconCls: 'treenode-no-icon', leaf: true}";
					} else {

						echo	(($jj)?(","):(""))."{
							label: '".$this->db->escape_str($d["name"])."',
							iconCls: 'treenode-no-icon',
							expanded: true,
							children:[
							";

						$kk = 0;
						foreach($d["children"] as $d2) {
							echo		(($kk)?(","):(""))."{label: '".$this->db->escape_str(anchor($d2["url"], $d2["name"], "onclick=\"return false;\" style=\"margin-left: -15px;\" "))."', url: '".(($d2["url"])?($d2["url"]):(""))."', title: '".$d2["name"]."', iconCls: 'treenode-no-icon', leaf: true}";
							$kk++;
						}

						echo	"]}";

					}
				$jj++;
				}
			}

			echo	"]}";

			$ii++;
		}
		echo	"]";
		return;

		echo	"[";
		$ii = 0;

		echo	"{
			label: '".$this->db->escape_str($this->lang->line("ADMIN"))."',
			iconCls: 'treenode-no-icon',
			expanded: true,
			children:[
			";
		foreach($arrMenu as $label => $url) {
			if(is_array($url)) {

				echo	(($ii)?(","):(""))."{
					label: '".$this->db->escape_str($label)."',
					iconCls: 'treenode-no-icon',
					expanded: true,
					children:[
					";

				$jj = 0;
				foreach($url["children"] as $childlabel => $childurl) {
					echo		(($jj)?(","):(""))."{label: '".$this->db->escape_str(anchor($childurl, $childlabel, "onclick=\"showMenu(this); return false;\" style=\"display: 'block'; margin-left: -15px;\" "))."', iconCls: 'treenode-no-icon', leaf: true}";
					$jj++;
				}

				echo	"]}";

			} else {
				echo		(($ii)?(","):(""))."{label: '".$this->db->escape_str(anchor($url, $label, "onclick=\"showMenu(this); return false;\" style=\"display: 'block'; margin-left: -15px;\" ".(($url == "logout")?("id=\"kilepes\""):(""))))."', iconCls: 'treenode-no-icon', leaf: true}";
			}
			$ii++;
		}
		echo	"]}]";
	}

	function login() {

		if(!$this->session->userdata("usrId")) {
			if($this->input->post("password") and $this->input->post("email")) {
				$this->load->model("user");
				$getUser = $this->user->getUser("usr_email = '".$this->db->escape_str($this->input->post("email"))."' and usr_password = '".md5($this->input->post("password"))."' and usr_verify is null");
				if($getUser) {
					$getUser = current($getUser);
					$this->session->set_userdata("usrId", $getUser["usrId"]);
					$this->session->set_userdata("usrEmail", $getUser["usrEmail"]);
					$this->session->set_userdata("usrNewsletter", $getUser["usrNewsletter"]);
					$this->session->set_userdata("grpName", $getUser["grpName"]);
					$this->session->set_userdata("usrProvider", $getUser["usrProvider"]);
					$this->session->set_userdata("fullName", $getUser["fullName"]);
					$this->user->update($getUser["usrId"], array("usr_logged" => $getUser["usrLogged"]+1));
					$this->db->trans_complete();
					redirect("admin/index");
				}
			}
			$this->page["content"] = $this->load->view("admin/login", NULL, TRUE);
			$this->load->view("template/admin_page", $this->page);
		} else {
			redirect("admin/index");
		}

	}

	function index() {
		$this->load->view("template/admin_page");
	}

	function user($panel = NULL) {
		//if(!Common::isSuperAdmin()) redirect("admin/index");
		if(Common::isAdmin()) {
			$this->load->view("admin/user", array("type" => "Admin"));
		} else {
			$this->load->view("admin/user".((is_null($panel))?("_tabpanel"):("")), array("type" => $panel));
		}
	}

	function get_user($type = NULL) {
		$this->load->model("user");
		$tgetUser = $this->user->getUser($where = ((!is_null($type) and $type == "Admin")?("u2g_usr_id is not null"):("u2g_usr_id is null")), $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		$getUser = array();
		if($tgetUser) {
			foreach($tgetUser as $d) {
				$getUser[] = $d;
			}
		}
		$return = array(
			"total" => $this->user->getUserCount($where = ((!is_null($type) and $type == "Admin")?("u2g_usr_id is not null"):("u2g_usr_id is null")), $this->input->get_post("fields"), $this->input->get_post("query")),
			"results" => $getUser
		);
		echo json_encode($return);
	}


	function category() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$subpage = array();
		$this->load->model("category");
		$subpage["getCategory"] = $this->category->getCategory();
		$this->load->view("admin/category", $subpage);
	}

	function getCatList($list = "") {
		$list = urldecode($list);
		$list = str_replace(array("&#40;", "&#41;"), array("(", ")"), $list);
		echo Common::arr2jsobj(explode("|", $list), $keytoobj = TRUE);
	}

	function category_insert_update() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$response = array("error" => "");
		$this->load->model("category");
		if($this->input->get_post("del")) {
			$this->category->delete($this->input->get_post("catId"));
		} elseif($this->input->get_post("sort") and intval($this->input->get_post("position"))) {
			$aktCat = $this->category->getCategory($where = "cat_id = '".$this->input->get_post("catId")."'");
			if(count($aktCat)) {
				$getCategory = $this->category->getCategory("cat_entity = '".key($aktCat)."'");
				if(intval($this->input->get_post("position")) <= count($getCategory[key($aktCat)])) {
					foreach($getCategory[key($aktCat)] as $ii => $category) {
						if($category["catId"] == $this->input->get_post("catId")) {
							if($category["catOrder"] < intval($this->input->get_post("position"))) {
								$mod = TRUE;
								$jj = $ii;
								while($mod) {
									$mod = FALSE;
									if(isset($getCategory[key($aktCat)][$jj+1]) and $getCategory[key($aktCat)][$jj+1]["catOrder"] <= intval($this->input->get_post("position"))) {
										$this->category->update($getCategory[key($aktCat)][$jj+1]["catId"], array("cat_order" => ($getCategory[key($aktCat)][$jj+1]["catOrder"] - 1)));
										$mod = TRUE;
										$jj++;
									}
								}
							} elseif($category["catOrder"] > intval($this->input->get_post("position"))) {
								$mod = TRUE;
								$jj = $ii;
								while($mod) {
									$mod = FALSE;
									if(isset($getCategory[key($aktCat)][$jj-1]) and $getCategory[key($aktCat)][$jj-1]["catOrder"] >= intval($this->input->get_post("position"))) {
										$this->category->update($getCategory[key($aktCat)][$jj-1]["catId"], array("cat_order" => ($getCategory[key($aktCat)][$jj-1]["catOrder"] + 1)));
										$mod = TRUE;
										$jj--;
									}
								}
							}
							$this->category->update($this->input->get_post("catId"), array("cat_order" => intval($this->input->get_post("position"))));
							return;
						}
					}
				}
			}
		} else {
			$insUpd = array(
				"cat_name" => $this->input->get_post("cat_name"),
				"cat_type" => $this->input->get_post("cat_type"),
				"cat_length" => (($this->input->get_post("cat_length"))?($this->input->get_post("cat_length")):(NULL)),
				"cat_entity" => $this->input->get_post("cat_entity"),
				"cat_required" => (($this->input->get_post("cat_required") == "I")?($this->input->get_post("cat_required")):("N")),
				"cat_highlight" => (($this->input->get_post("cat_highlight") == "I")?($this->input->get_post("cat_highlight")):("N")),
			);
			if($this->input->get_post("cat_type") == "L") {
				$insUpd["cat_list"] = implode("|", $this->input->get_post("cat_list"));
			} else {
				$insUpd["cat_list"] = NULL;
			}
			if($this->input->get_post("cat_id")) {
				$this->category->update($this->input->get_post("cat_id"), $insUpd);
			} else {
				$insUpd["cat_order"] = $this->category->getOrderToInsert($where = "cat_entity = '".$this->db->escape_str($this->input->get_post("cat_entity"))."'");
				$this->category->insert($insUpd);
			}
		}

		echo	json_encode(array("success" => true) + $response);
	}

	function data_edit($entity = NULL) {
		$subpage = array();

		$editable = array();
		if(is_null($entity)) {
			$editable = array(
				"CON" => Common::isSuperAdmin(),
				"COU" => Common::isAdminJog("COU"),
				"CITY" => Common::isAdminJog("CITY"),
				"INS" => (Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_IMP")),
				"FAC" => (Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_FAC")),
				"ACC" => (Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_ACC")),
				"MAJ" => (Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_MAJ")),
				"SCH" => (Common::isAdminJog("INS") and Common::isAdminJog("PAGE_CAT_SCH")),
			);

			/*
			if(!Common::isSuperAdmin()) {
				$this->load->model("continent");
				$getContinent = $this->continent->getContinentList();
				foreach($getContinent as $conId => $conData) {
					if(isset($conData["cou"])) {
						foreach($conData["cou"] as $couId => $couData) {
							if($couData["szerk"]) {
								$editable["COU"] = TRUE;
								$editable["CITY"] = TRUE;
								//$editable["INS"] = TRUE; // added
							}
							if(isset($couData["city"])) {
								foreach($couData["city"] as $cityId => $cityData) {
									if($cityData["szerk"]) {
										$editable["CITY"] = TRUE;
										//$editable["INS"] = TRUE; // added
									}
									if(isset($cityData["ins"])) {
										foreach($cityData["ins"] as $insId => $insData) {
											if($insData["szerk"]) {
												$editable["INS"] = TRUE;
												$editable["MAJ"] = TRUE;
												$editable["SCH"] = TRUE;
											}
										}
									}
								}
							}
						}
					}
				}
			}
			*/
			//Common::pr($editable);
			//Common::pr($getContinent);
		}

		$this->load->view("admin/data_edit".((!is_null($entity))?("_".$entity):("")), $subpage = array("editable" => $editable));
	}

	function data_edit_insert_update() {

		$response = array("error" => "");

		if($this->input->get_post("publish") !== FALSE) {

			$this->load->model("ent2cat");
			$getEnt2cat = $this->ent2cat->getEnt2cat($where = "e2c_entity = '".$this->db->escape_str($this->input->get_post("ENTITY"))."' and e2c_ent_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
			foreach($getEnt2cat as $d) {
				if($d["e2cTempFlag"] == "I" or $this->input->get_post("publish") == 2) {
					$insUpd = array(
						"e2c_temp" => NULL,
						"e2c_temp_flag" => "N",
					);
					if($this->input->get_post("publish") == 1) {
						$insUpd["e2c_int"] = ((is_numeric($d["e2cTemp"]))?($d["e2cTemp"]):(NULL));
						$insUpd["e2c_text"] = ((!is_numeric($d["e2cTemp"]))?(preg_replace('/class=".*?"/', '', $d["e2cTemp"])):(NULL));
					} elseif($this->input->get_post("publish") == 2) {
						$insUpd["e2c_int"] = NULL;
						$insUpd["e2c_text"] = NULL;
						$insUpd["e2c_temp"] = Common::coalesce(array($d["e2cInt"], $d["e2cText"], $d["e2cTemp"]));
						$insUpd["e2c_temp_flag"] = "I";
					}
					$this->ent2cat->update($d["e2cId"], $insUpd);
				}
			}

		} else {

			switch($this->input->post("ENTITY")) {

				case "USER": {
					$this->load->model("user");
					if($this->input->get_post("del")) {
						$this->user->delete($this->input->get_post("usrId"));
					} else {

						if($this->input->get_post("usr_email")) {
							$getUser = $this->user->getUser($where = "usr_email = '".$this->db->escape_str($this->input->get_post("usr_email"))."' and usr_id <> '".$this->db->escape_str($this->input->get_post("usr_id"))."'");
							if($getUser) {
								$response["error"] .= $this->lang->line("THE_E-MAIL_ADDRESS_IS_RESERVED_PLEASE_SELECT_AN_OTHER")."<br/>";
							}
							if(!preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->post("usr_email"))) {
								$response["error"] .= $this->lang->line("THE_FORMAT_OF_THE_E-MAIL_ADDRESS_IS_INCORRECT")."<br/>";
							}
						} else {
							$response["error"] .= $this->lang->line("E-MAIL_ADDRESS_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("usr_id") and !$this->input->get_post("usr_password")) {
							$response["error"] .= $this->lang->line("PASSWORD_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("usr_password") and $this->input->get_post("usr_password") <> $this->input->get_post("usr_password_re")) {
							$response["error"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd["usr_email"] = $this->input->get_post("usr_email");
							if($this->input->get_post("usr_password")) {
								$insUpd["usr_password"] = md5($this->input->get_post("usr_password"));
							}
							if($this->input->get_post("usr_id")) {
								$this->user->update($this->input->get_post("usr_id"), $insUpd);
								$usrId = $this->input->get_post("usr_id");
							} else {
								if(is_array($this->session->userdata("grpName")) and Common::isAdmin()) {
									$insUpd["usr_createdby_grp_id"] = "2";
								}
								$insUpd["usr_registered"] = Common::now();
								$usrId = $_POST["ID"] = $this->user->insert($insUpd);
							}

							$this->load->model("usr2grp");
							$getUsr2grp = $this->usr2grp->getUsr2grp($where = "u2g_usr_id = '".$usrId."'");
							$groupChangeFromNonverified2Admin = 0;
							
							foreach($getUsr2grp as $grp_id => $u2g_id) {
								$this->usr2grp->delete($u2g_id);
								if($grp_id == 3) {
									$groupChangeFromNonverified2Admin++;
								}
							}

							$this->load->model("usr2ent");
							$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$usrId."'");
							foreach($getUsr2ent as $ENTITY => $d) {
								if(in_array($ENTITY, array("COU", "CITY"))) {
									foreach($d["u2eIds"] as $u2e_id) {
										$this->usr2ent->delete($u2e_id);
									}
								} elseif($ENTITY == "INS") {
									if(!is_array($this->input->post("ins_id"))) {
										$_POST["ins_id"] = array();
									}
									foreach($d["children"] as $ii => $insId) {
										if(!in_array($insId, $this->input->post("ins_id"))) {
											$this->usr2ent->delete($d["u2eIds"][$ii]);
											foreach($getUsr2ent as $innerEntity => $innerD) {
												if(substr($innerEntity, 0, 8) == "PAGE_CAT") {
													foreach($innerD["u2eIds"] as $innerInsId => $innerU2eId) {
														if($insId == $innerInsId) {
															$this->usr2ent->delete($innerU2eId);
														}
													}
												}
											}
										}
									}
								}
							}

							$u2eInsert = FALSE;

							if($this->input->post("cou_id")) {
								foreach($this->input->post("cou_id") as $couId) {
									if($couId) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_cou_id" => $couId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("city_id")) {
								foreach($this->input->post("city_id") as $cityId) {
									if($cityId) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_city_id" => $cityId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("ins_id")) {
								foreach($this->input->post("ins_id") as $insId) {
									if($insId and !in_array($insId, ((isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array())))) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_ins_id" => $insId));
										$u2eInsert = TRUE;
									}
								}
							}

							if($this->input->post("page_cat")) {
								foreach($this->input->post("page_cat") as $page_cat_name) {
									if($page_cat_name) {
										$this->usr2ent->insert(array("u2e_usr_id" => $usrId, "u2e_page_cat" => $page_cat_name));
										$u2eInsert = TRUE;
									}
								}
							}

							if($u2eInsert or $this->input->post("u2g_grp_id")) {
								// ID -2 (Admin)
								$u2g_grp_id = ($this->input->post("u2g_grp_id")?$this->input->post("u2g_grp_id"):2);
								$this->usr2grp->insert(array("u2g_usr_id" => $usrId, "u2g_grp_id" => $u2g_grp_id));
								if($u2g_grp_id == 2) {
									$groupChangeFromNonverified2Admin++;
								}
							}
							
							// not verfied adminból, vagy nem admin userból admin user lett
							if($groupChangeFromNonverified2Admin > 1) {
								$this->load->model("user");
								$getUser = $this->user->getUser("usr_id = '".intval($usrId)."'");
								Common::sendEmail($getUser[$usrId]["usrEmail"], $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_SUBJECT"), $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_BODY"), $replace = NULL, $attach = NULL);
							}

						}

					}
				} break;

				case "CON": {
					$this->load->model("continent");
					if($this->input->get_post("del")) {
						$this->continent->delete($this->input->get_post("ID"));
					} else {
						if(!$this->input->get_post("con_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_CONTINENT_IS_REQUIRED");
						} else {
							$insUpd = array(
								"con_name" => $this->input->get_post("con_name"),
								"con_url_name" => url_title($this->input->get_post("con_name"), "underscore", TRUE),
							);
							if($this->input->get_post("ID") > 0) {
								$this->continent->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->continent->insert($insUpd);
							}
						}
					}

				} break;

				case "COU": {
					$this->load->model("country");
					if($this->input->get_post("del")) {
						$this->country->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("cou_name")) {
							$response["error"] .= $this->lang->line("COUNTRY_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("cou_con_id")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_CONTINENT_IS_REQUIRED")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd = array(
								"cou_name" => $this->input->get_post("cou_name"),
								"cou_url_name" => url_title($this->input->get_post("cou_name"), "underscore", TRUE),
								"cou_con_id" => $this->input->get_post("cou_con_id"),
								"cou_latitude" => (($this->input->get_post("cou_latitude"))?($this->input->get_post("cou_latitude")):(NULL)),
								"cou_longitude" => (($this->input->get_post("cou_longitude"))?($this->input->get_post("cou_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->country->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->country->insert($insUpd);
							}
						}
					}
				} break;

				case "CITY": {
					$this->load->model("city");
					if($this->input->get_post("del")) {
						$this->city->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("city_name")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("city_cou_id")) {
							$response["error"] .= $this->lang->line("COUNTRY_IS_REQUIRED")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd = array(
								"city_name" => $this->input->get_post("city_name"),
								"city_url_name" => url_title($this->input->get_post("city_name"), "underscore", TRUE),
								"city_cou_id" => $this->input->get_post("city_cou_id"),
								"city_latitude" => (($this->input->get_post("city_latitude"))?($this->input->get_post("city_latitude")):(NULL)),
								"city_longitude" => (($this->input->get_post("city_longitude"))?($this->input->get_post("city_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->city->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->city->insert($insUpd);
							}
						}
					}
				} break;

				case "INS": {
					$this->load->model("institute");
					if($this->input->get_post("del")) {
						$this->load->model("major");
						$getMajor = $this->major->getMajor($where = "maj_ins_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
						foreach($getMajor as $majData) {
							$this->major->delete($majData["majId"]);
						}
						$this->institute->delete($this->input->get_post("ID"));
						// karok törlése
						$getChildren = $this->institute->getChildren($this->input->get_post("ID"));
						foreach($getChildren as $ins) {
							if(isset($ins["insId"])) {
								$this->institute->delete($ins["insId"]);
							}
						}
					} else {

						if(!$this->input->get_post("ins_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!(Common::isAdmin() and $this->input->get_post("ID") < 0)) { // intezmenyi usernek mas form uj felvetelnel
							if(!$this->input->get_post("ins_city_id")) {
								$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
							}

							if($this->input->get_post("ins_ins_id") and $this->input->get_post("ins_ins_id") === $this->input->get_post("ID")) {
								$response["error"] .= $this->lang->line("PARENT_DOES_NOT_MATCH_WITH_THE_SELECTED_INSTITUTE")."<br/>";
							}
						}

						if(!$response["error"]) {
							if(Common::isAdmin() and $this->input->get_post("ID") < 0) {
								$this->load->model("usr2grp");
								if($this->usr2grp->checkInsRegistration($this->session->userdata("usrId"))) {
									$response["message"] = $this->lang->line("INSTITUTE_REGISTRATION_IN_PROGRESS");
								} else {
									define("OVERRIDE", 1);
									$this->load->model("institute");
									$getInstitute = $this->institute->getInstitute($where = "ins_name = '".$this->db->escape_str($this->input->post("ins_name"))."'");
									
									$this->usr2grp->update(
										$this->usr2grp->getUsr2grpId("u2g_usr_id = ".intval($this->session->userdata("usrId"))),
										array(
											"u2g_ins_id" => ((count($getInstitute))?($getInstitute[0]["insId"]):(NULL)),
											"u2g_ins_name" => ((count($getInstitute))?(NULL):($this->input->post("ins_name"))),
											"u2g_ins_address" => ((count($getInstitute))?(NULL):($this->input->post("ins_address"))),
											"u2g_ins_website" => ((count($getInstitute))?(NULL):($this->input->post("ins_website"))),
											"u2g_ins_address_raw" => ((count($getInstitute))?(NULL):($this->input->post("u2g_ins_address_raw"))),
											"u2g_city_id" => ((count($getInstitute))?(NULL):($this->input->post("u2g_city_id"))),
											"u2g_postal_code" => ((count($getInstitute))?(NULL):($this->input->post("u2g_postal_code"))),
										)
									);
									// TODO
									/*
									// pdf
									$replace = array("<INS_NAME>" => ((count($getInstitute))?($getInstitute[0]["insName"]):($this->input->post("ins_name"))));
									$replace["<ADDRESS_OF_INSTITUTE>"] = $this->input->post("ins_website");
									$replace["<INS_NAME>"] = $this->input->post("insName");
									$replace["<URL_OF_INSTITUTE>"] = $this->input->post("insWebsite");
									$replace["<USR_EMAIL>"] = $this->session->userdata("usrEmail");
									$replace["<FULL_NAME>"] = (($this->session->userdata("fullName"))?($this->session->userdata("fullName")):($replace["<USR_EMAIL>"]));
									$this->_gen_pdf(str_replace(array_keys($replace), $replace, $this->lang->line("ADMIN_REGISTRATION_PDF")), "reg_".$this->session->userdata("usrId").".pdf");
									$path_to_the_file = realpath(APPPATH."../".PDFS."reg_".$this->session->userdata("usrId").".pdf");

									// email
									Common::sendEmail($this->input->post("usrEmail"), $this->lang->line("ADMIN_NEW_INSTITUTE_REGISTRATION_SUBJECT"), $this->lang->line("ADMIN_NEW_INSTITUTE_REGISTRATION_EMAIL"), $replace, $path_to_the_file);
									*/
									$response["message"] = $this->lang->line("INSTITUTE_REGISTRATION_STARTED");
								}
							} else {
								$insUpd = array(
									"ins_ins_id" => (($this->input->get_post("ins_ins_id"))?($this->input->get_post("ins_ins_id")):(NULL)),
									"ins_name" => $this->input->get_post("ins_name"),
									"ins_url_name" => url_title($this->input->get_post("ins_name"), "underscore", TRUE),
									"ins_city_id" => $this->input->get_post("ins_city_id"),
									"ins_latitude" => (($this->input->get_post("ins_latitude"))?($this->input->get_post("ins_latitude")):(NULL)),
									"ins_longitude" => (($this->input->get_post("ins_longitude"))?($this->input->get_post("ins_longitude")):(NULL)),
								);
								if($this->input->get_post("ID") > 0) {
									$this->institute->update($this->input->get_post("ID"), $insUpd);
								} else {
									$_POST["ID"] = $this->institute->insert($insUpd);
									
									/*if(Common::isAdmin()) {
										$this->load->model("usr2ent");
										$this->usr2ent->insert(
											array(
												"u2e_usr_id" => $this->session->userdata("usrId"),
												"u2e_ins_id" => $_POST["ID"],
											)
										);
									}*/
								}
							}
							$this->institute->fixUrlNames();
						}
					}
				} break;

				case "FAC": {
					$this->load->model("institute");
					if($this->input->get_post("del")) {
						$this->load->model("major");
						$getMajor = $this->major->getMajor($where = "maj_ins_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
						foreach($getMajor as $majData) {
							$this->major->delete($majData["majId"]);
						}
						$this->institute->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("ins_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("ins_city_id")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if($this->input->get_post("ins_ins_id") and $this->input->get_post("ins_ins_id") === $this->input->get_post("ID")) {
							$response["error"] .= $this->lang->line("PARENT_DOES_NOT_MATCH_WITH_THE_SELECTED_INSTITUTE")."<br/>";
						}

						if(!$response["error"]) {
							$insUpd = array(
								"ins_ins_id" => (($this->input->get_post("ins_ins_id"))?($this->input->get_post("ins_ins_id")):(NULL)),
								"ins_name" => $this->input->get_post("ins_name"),
								"ins_url_name" => url_title($this->input->get_post("ins_name"), "underscore", TRUE),
								"ins_city_id" => $this->input->get_post("ins_city_id"),
								"ins_latitude" => (($this->input->get_post("ins_latitude"))?($this->input->get_post("ins_latitude")):(NULL)),
								"ins_longitude" => (($this->input->get_post("ins_longitude"))?($this->input->get_post("ins_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->institute->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->institute->insert($insUpd);
								if(Common::isAdmin()) {
									$this->load->model("usr2ent");
									$this->usr2ent->insert(
										array(
											"u2e_usr_id" => $this->session->userdata("usrId"),
											"u2e_ins_id" => $_POST["ID"],
										)
									);
									$this->usr2ent->insert(
										array(
											"u2e_usr_id" => $this->session->userdata("usrId"),
											"u2e_ins_id" => $_POST["ID"],
											"u2e_page_cat" => "FAC",
										)
									);
								}
							}
							$this->institute->fixUrlNames();
						}
					}
				} break;

				case "ACC": {
					$this->load->model("accomodation");
					if($this->input->get_post("del")) {
						$this->accomodation->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("acc_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_ACCOMODATION_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("acc_city_id")) {
							$response["error"] .= $this->lang->line("CITY_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("ins_id")) {
							$response["error"] .= $this->lang->line("THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}
						
						if(!$response["error"]) {
							$insUpd = array(
								"acc_name" => $this->input->get_post("acc_name"),
								"acc_url_name" => url_title($this->input->get_post("acc_name"), "underscore", TRUE),
								"acc_city_id" => $this->input->get_post("acc_city_id"),
								"acc_latitude" => (($this->input->get_post("acc_latitude"))?($this->input->get_post("acc_latitude")):(NULL)),
								"acc_longitude" => (($this->input->get_post("acc_longitude"))?($this->input->get_post("acc_longitude")):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->accomodation->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->accomodation->insert($insUpd);
							}
							
							// ins
							$this->load->model("acc2ins_maj");
							$getAcc2ins_majIds = $this->acc2ins_maj->getAcc2ins_majIds($where = "a2im_acc_id = '".$this->input->get_post("ID")."' and a2im_ins_id is not null");
							$deletedInsId = array();
							foreach($getAcc2ins_majIds as $a2imId => $a2imData) {
								$this->acc2ins_maj->delete($a2imId);
								$deletedInsId[$a2imData["a2imInsId"]] = $a2imData["a2imInsId"];
							}
							if($this->input->post("ins_id")) {
								foreach($this->input->post("ins_id") as $insId) {
									if($insId) {
										$this->acc2ins_maj->insert(array("a2im_acc_id" => $this->input->get_post("ID"), "a2im_ins_id" => $insId));
										if(isset($deletedInsId[$insId])) unset($deletedInsId[$insId]);
									}
								}
							}
							
							// major - acc kötések rendberakása
							if(count($deletedInsId)) {
								$this->acc2ins_maj->deleteAcc2ins_byDeletedInsIds($deletedInsId);
							}
						}
					}
				} break;
				
				case "MAJ": {
					$this->load->model("major");
					if($this->input->get_post("del")) {
						$this->major->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("maj_name")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_COURSE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_ins_id")) {
							$response["error"] .= $this->lang->line("NAME_OF_THE_INSTITUTE_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_sub_id")) {
							$response["error"] .= $this->lang->line("SUBJECT_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_prog_type")) {
							$response["error"] .= $this->lang->line("TYPE_OF_THE_SCHOOL_IS_REQUIRED")."<br/>";
						}

						if(!$this->input->get_post("maj_prog_type2")) {
							$response["error"] .= $this->lang->line("PROGRAM_TYPE_IS_REQUIRED")."<br/>";
						}

						if(!$response["error"]) {

							$tmp_url_name = $url_name = url_title($this->input->get_post("maj_name"), "underscore", TRUE);
							$free = FALSE;
							$counter = 1;
							while(!$free) {
								$free = TRUE;
								$getMajor = $this->major->getMajor($where = "maj_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("ID") > 0)?(" and maj_id <> '".$this->db->escape_str($this->input->get_post("ID"))."' "):("")));
								if($getMajor) {
									$free = FALSE;
									$url_name = $tmp_url_name.$counter;
									$counter++;
								}
							}

							$insUpd = array(
								"maj_name" => $this->input->get_post("maj_name"),
								"maj_url_name" => $url_name, //url_title($this->input->get_post("maj_name"), "underscore", TRUE),
								"maj_ins_id" => $this->input->get_post("maj_ins_id"),
								"maj_sub_id" => $this->input->get_post("maj_sub_id"),
								"maj_prog_type" => $this->input->get_post("maj_prog_type"),
								"maj_prog_type2" => $this->input->get_post("maj_prog_type2"),
								"maj_list_from_date" => (($this->input->get_post("maj_list_from_date"))?(Common::dateToDatabase($this->input->get_post("maj_list_from_date"))):(NULL)),
								"maj_list_till_date" => (($this->input->get_post("maj_list_till_date"))?(Common::dateToDatabase($this->input->get_post("maj_list_till_date"))):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->major->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->major->insert($insUpd);
							}
							
							// acc
							$this->load->model("acc2ins_maj");
							$getAcc2ins_majIds = $this->acc2ins_maj->getAcc2ins_majIds($where = "a2im_maj_id = ".intval($_POST["ID"]));
							foreach($getAcc2ins_majIds as $a2imId) {
								$this->acc2ins_maj->delete($a2imId);
							}
							if($this->input->post("acc_id")) {
								foreach($this->input->post("acc_id") as $accId) {
									if($accId) {
										$this->acc2ins_maj->insert(array("a2im_acc_id" => $accId, "a2im_maj_id" => $this->input->get_post("ID")));
									}
								}
							}
							
						}
					}
				} break;

				case "SCH": {
					$this->load->model("scholarship");
					if($this->input->get_post("del")) {
						$this->scholarship->delete($this->input->get_post("ID"));
					} else {

						if(!$this->input->get_post("sch_name")) {
							$response["error"] .= $this->lang->line("THE_SCHOLARSHIP_NAME_IS_REQUIRED")."<br/>";
						}

						if(!(($this->input->get_post("ins_id") and isset($_POST["ins_id"][0]) and $_POST["ins_id"][0]) or ($this->input->get_post("maj_id") and isset($_POST["maj_id"][0]) and $_POST["maj_id"][0]))) {
							$response["error"] .= $this->lang->line("SET_AT_LEAST_ONE_INSTITUTE_OR_MAJOR")."<br/>";
						}
						
						if(!$response["error"]) {

							$tmp_url_name = $url_name = url_title($this->input->get_post("sch_name"), "underscore", TRUE);
							$free = FALSE;
							$counter = 1;
							while(!$free) {
								$free = TRUE;
								$getScholarship = $this->scholarship->getScholarship($where = "sch_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("ID") > 0)?(" and sch_id <> '".$this->db->escape_str($this->input->get_post("ID"))."' "):("")));
								if($getScholarship) {
									$free = FALSE;
									$url_name = $tmp_url_name.$counter;
									$counter++;
								}
							}

							$insUpd = array(
								"sch_name" => $this->input->get_post("sch_name"),
								"sch_url_name" => $url_name,
								"sch_sub_id" => (($this->input->get_post("sch_sub_id"))?($this->input->get_post("sch_sub_id")):(NULL)),
								"sch_list_date" => (($this->input->get_post("sch_list_date"))?(Common::dateToDatabase($this->input->get_post("sch_list_date"))):(NULL)),
							);
							if($this->input->get_post("ID") > 0) {
								$this->scholarship->update($this->input->get_post("ID"), $insUpd);
							} else {
								$_POST["ID"] = $this->scholarship->insert($insUpd);
							}
							
							// sch2 tabla torlese es feltoltese
							$this->load->model("sch2cou_ins_maj");
							$getScholarship = $this->scholarship->getScholarship("sch_id = '".$this->db->escape_str($this->input->get_post("ID"))."'");
							foreach(array("ins", "cou", "maj") as $entity) {
								if(!isset($_POST[$entity."_id"]) or !is_array($_POST[$entity."_id"])) {
									$_POST[$_POST[$entity."_id"]] = array();
								}
								if(isset($getScholarship[0][strtoupper($entity)])) {
									foreach($getScholarship[0][strtoupper($entity)] as $entId => $entData) {
										if(!in_array($entId, $this->input->post($entity."_id"))) {
											// delete
											$this->sch2cou_ins_maj->delete($entData["s2cId"]);
										}
									}
								}
								
								foreach($this->input->post($entity."_id") as $entId) {
									if($entId and !isset($getScholarship[0][strtoupper($entity)][$entId])) {
										// insert
										$this->sch2cou_ins_maj->insert(array(
											"s2c_sch_id" => $this->input->get_post("ID"),
											"s2c_".$entity."_id" => $entId,
										));
									}
								}
								
							}
							
						}
					}
				} break;
				
			}

			if(!defined("AUTH_ERROR")) {
				$this->entity_insert_update($this->input->post("ENTITY"), abs($this->input->get_post("ID")));
			}

		}

		echo	json_encode(array("success" => true) + $response);

	}

	function entity_insert_update($entity, $id) {
		$this->load->model("ent2cat");
		$getEnt2cat = $this->ent2cat->getEnt2cat($where = "e2c_entity = '".$this->db->escape_str($entity)."' and e2c_ent_id = '".$this->db->escape_str($id)."' ");
		
		// clean html attributes
		foreach($_POST as $key => $val) {
			if(preg_match("/cat_[0-9]*/msi", $key) and trim(strip_tags($val))) {
				$catId = mb_substr($key, 4);
				$_POST["cat_".$catId] = $this->input->post("cat_".$catId, TRUE);
				/*
				if(is_string($this->input->post("cat_".$catId))) {
					$dom = new DOMDocument;
					echo "cat_".$catId."<br/>"; var_dump($_POST["cat_".$catId]);
					$dom->loadHTML($_POST["cat_".$catId]);
					$xpath = new DOMXPath($dom);
					$nodes = $xpath->query('//@*');
					foreach ($nodes as $node) {
						if(!in_array($node->nodeName, array("href", "width", "height", "src", "alt", "title", "border", "align", "font-family", "color", "marker"))) {
							$node->parentNode->removeAttribute($node->nodeName);
						}
					}
				}
				*/
				//$_POST["cat_".$catId] = $dom->saveHTML();
				$_POST["cat_".$catId] = preg_replace('/class=".*?"/', '', $_POST["cat_".$catId]);
				$_POST["cat_".$catId] = preg_replace('/style=".*?"/', '', $_POST["cat_".$catId]);
				$_POST["cat_".$catId] = preg_replace('/id=".*?"/', '', $_POST["cat_".$catId]);
				//$_POST["cat_".$catId] = strip_tags($_POST["cat_".$catId], "<p><a><img><span><div><i><b><strong><u><font><ul><ol><li>");
			}
			// date overwrite
			if(preg_match("/cat_[0-9]*_day/msi", $key)) {
				$catId = mb_substr($key, 4, strlen($key)-8);
				// day
				$_POST["cat_".$catId."_day"] = intval($_POST["cat_".$catId."_day"]);
				if($_POST["cat_".$catId."_day"] >= 1 and $_POST["cat_".$catId."_day"] <= 31) {
					$_POST["cat_".$catId."_day"] = str_pad($_POST["cat_".$catId."_day"], 2, 0, STR_PAD_LEFT);
				} else {
					$_POST["cat_".$catId."_day"] = "";
				}
				// month
				$_POST["cat_".$catId."_month"] = intval($_POST["cat_".$catId."_month"]);
				if($_POST["cat_".$catId."_month"] >= 1 and $_POST["cat_".$catId."_month"] <= 12) {
					$_POST["cat_".$catId."_month"] = str_pad($_POST["cat_".$catId."_month"], 2, 0, STR_PAD_LEFT);
				} else {
					$_POST["cat_".$catId."_month"] = "";
				}
				// year
				$_POST["cat_".$catId."_year"] = intval($_POST["cat_".$catId."_year"]);
				
				if(!checkdate ( intval($_POST["cat_".$catId."_month"]) , intval($_POST["cat_".$catId."_day"]) , intval($_POST["cat_".$catId."_year"]) )) {
					$_POST["cat_".$catId."_day"] = "";
				}
				
				$_POST["cat_".$catId] = (($this->input->post("cat_".$catId."_month"))?($this->input->post("cat_".$catId."_month")."."):("")) . (($this->input->post("cat_".$catId."_day"))?($this->input->post("cat_".$catId."_day")."."):("")) . $this->input->post("cat_".$catId."_year");
				unset($_POST["cat_".$catId."_day"]);
				unset($_POST["cat_".$catId."_month"]);
				unset($_POST["cat_".$catId."_year"]);
			}
		}
		
		foreach($getEnt2cat as $catId => $catData) {
			if(!$this->input->post("cat_".$catId)) {
				$this->ent2cat->delete($catData["e2cId"]);
			} else {
				$insUpd = array (
					//"e2c_int" => ((is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
					//"e2c_text" => ((!is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
					"e2c_temp" => (($entity == "USER")?(NULL):(($this->input->post("cat_".$catId)))),
					"e2c_temp_flag" => (($entity == "USER")?("N"):("I")),
				);
				if($entity == "USER") {
					$insUpd["e2c_text"] = $this->input->post("cat_".$catId);
				}
				$this->ent2cat->update($catData["e2cId"], $insUpd);
			}
		}
		foreach($_POST as $key => $val) {
			if(preg_match("/cat_[0-9]*/msi", $key) and trim(strip_tags($val))) {
				$catId = mb_substr($key, 4);
				if(!isset($getEnt2cat[$catId])) {
					$insUpd = array(
						"e2c_entity" => $entity,
						"e2c_ent_id" => $id,
						"e2c_cat_id" =>	$catId,
						//"e2c_int" => ((is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
						//"e2c_text" => ((!is_numeric($this->input->post("cat_".$catId)))?($this->input->post("cat_".$catId)):(NULl)),
						"e2c_temp" => (($entity == "USER")?(NULL):($this->input->post("cat_".$catId))),
						"e2c_text" => (($entity != "USER")?(NULL):($this->input->post("cat_".$catId))),
						"e2c_temp_flag" => (($entity == "USER")?("N"):("I")),
					);
					$this->ent2cat->insert($insUpd);
				}
			}
		}
	}

	function deprecated_getContinentList() {
		header("Content-type:text/javascript");
		$this->load->model("continent");
		$getContinent = $this->continent->getContinentList();
		echo	"[";
		if(count($getContinent)) {
			$elsoCon = TRUE;
			foreach($getContinent as $conId => $conData) {
				if(!$elsoCon) echo	",";
				echo	"{";
				echo		"name: '".$conData["conName"]."',";
				echo		"szerk: ".(($conData["szerk"])?("true"):("false")).",";
				echo		"temp: ".((isset($conData["temp"]))?("true"):("false")).",";
				echo		"url: '".$conData["previewUrl"]."',";
				echo		"entity: 'CON_".$conId."', expanded:true,";
				if(isset($conData["cou"])) {
					echo		"iconCls:'task-folder',";
					echo		"children: [";
					$elsoCou = TRUE;
					foreach($conData["cou"] as $couId => $couData) {
						if(!$elsoCou) echo		",";
						echo	"{";
						echo		"name: '".$couData["couName"]."',";
						echo		"szerk: ".(($couData["szerk"])?("true"):("false")).",";
						echo		"temp: ".((isset($couData["temp"]))?("true"):("false")).",";
						echo		"url: '".$couData["previewUrl"]."',";
						echo		"entity: 'COU_".$couId."', expanded:true,";
						if(isset($couData["city"])) {
							echo		"iconCls:'task-folder',";
							echo		"children: [";
							$elsoCity = TRUE;
							foreach($couData["city"] as $cityId => $cityData) {
								if(!$elsoCity) echo		",";
								echo	"{";
								echo		"name: '".$cityData["cityName"]."',";
								echo		"szerk: ".(($cityData["szerk"])?("true"):("false")).",";
								echo		"temp: ".((isset($cityData["temp"]))?("true"):("false")).",";
								echo		"url: '".$cityData["previewUrl"]."',";
								echo		"entity: 'CITY_".$cityId."', expanded:true,";
								if(isset($cityData["ins"])) {
									echo		"iconCls:'task-folder',";
									echo		"children: [";
									$elsoIns = TRUE;
									foreach($cityData["ins"] as $insId => $insData) {
										if(!$elsoIns) echo		",";
										echo	"{";
										echo		"name: '".$insData["insName"]."',";
										echo		"szerk: ".(($insData["szerk"])?("true"):("false")).",";
										echo		"temp: ".((isset($insData["temp"]))?("true"):("false")).",";
										echo		"url: '".$insData["previewUrl"]."',";
										echo		"entity: 'INS_".$insId."', expanded:true,";
										if(isset($insData["maj"])) {
											echo		"iconCls:'task-folder',";
											echo		"children: [";
											$elsoMaj = TRUE;
											foreach($insData["maj"] as $majId => $majData) {
												if(!$elsoMaj) echo		",";
												echo	"{";
												echo		"name: '".$majData["majName"]."',";
												echo		"szerk: true,";
												echo		"temp: ".((isset($majData["temp"]))?("true"):("false")).",";
												echo		"url: '".$majData["previewUrl"]."',";
												echo		"entity: 'MAJ_".$majId."',";
												echo		"iconCls:'task',";
												echo		"leaf: true";
												echo	"}";
												$elsoMaj = FALSE;
											}
											echo		"]";
										} else {
											echo		"leaf: true,";
											echo		"iconCls: 'task'";
										}
										echo	"}";
										$elsoIns = FALSE;
									}
									echo		"]";
								} else {
									echo		"leaf: true,";
									echo		"iconCls: 'task'";
								}
								echo	"}";
								$elsoCity = FALSE;
							}
							echo		"]";
						} else {
							echo		"leaf: true,";
							echo		"iconCls: 'task'";
						}
						echo	"}";
						$elsoCou = FALSE;
					}
					echo		"]";
				} else {
					echo		"leaf: true,";
					echo		"iconCls: 'task'";
				}
				echo	"}";
				$elsoCon = FALSE;
			}
		}
		echo	"]";
	}

	function getCategoryVal() {
		header("Content-type:text/javascript");
		$this->load->model("category");
		//$getCategoryVal = $this->category->getCategoryVal((($this->input->post("entity") == "FAC")?("INS"):($this->input->post("entity"))), $this->input->post("id"));
		$getCategoryVal = $this->category->getCategoryVal($this->input->post("entity"), $this->input->post("id"));

		// temp adatokkal feluliras
		foreach($getCategoryVal as $catId => $catData) {
			if($catData["e2cTempFlag"] == "I") {
				$getCategoryVal[$catId]["val"] = $catData["e2cTemp"];
			}
		}

		$windowTitle = $formElements = "";

		switch($this->input->post("entity")) {

			case "USER": {
				$this->load->model("user");
				$superUserEnable = FALSE;
				if(substr($this->input->post("id"), 0, 2) == "--") {
					$superUserEnable = TRUE;
					$_POST["id"] = substr($this->input->post("id"), 1);
				}
				$getUser = $this->user->getUser("usr_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getUser) {
					$windowTitle = $getUser[$this->input->post("id")]["usrEmail"];
				} elseif(Common::isAdmin()) {
					$adminUser = current($this->user->getUser("usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'"));
				}
				//Common::pr($getUser); exit;
				$formElements .=	((isset($getUser[$this->input->post("id")]))?
													("{
														hidden: true,
														inputType: 'hidden',
														name: 'usr_id',
														value: '".$this->db->escape_str($this->input->post("id"))."'
													},"):(""))."
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("GROUP"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("GROUP"))."',
																hiddenName:'u2g_grp_id',
																store: new Ext.data.ArrayStore({
																	fields: ['grp_id', 'grp_name'],
																	url: '".site_url()."admin/getGroup".(($superUserEnable)?("/SUPERADMIN"):(""))."',
																	autoLoad: true
																}),
																valueField:'grp_id',
																displayField:'grp_name',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: ".((Common::isSuperAdmin())?("true"):("false")).",
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getUser[$this->input->post("id")]["grpName"]))?("hiddenValue: '".$this->db->escape_str(key($getUser[$this->input->post("id")]["grpName"]))."',"):(""))."
																".((isset($getUser[$this->input->post("id")]["grpName"]))?("value: '".$this->db->escape_str(current($getUser[$this->input->post("id")]["grpName"]))."',"):(""))."
																anchor:'100%'
															})]
													},{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("E-MAIL_ADDRESS"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("E-MAIL_ADDRESS"))."',
															name: 'usr_email',
															".((isset($getUser[$this->input->post("id")]))?("value:'".$this->db->escape_str($getUser[$this->input->post("id")]["usrEmail"])."',"):(""))."
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
														}]
													},{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("PASSWORD"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.ux.PasswordMeter({
																xtype: 'textfield',
																inputType: 'password',
																id: 'password',
																fieldLabel: '".$this->db->escape_str($this->lang->line("PASSWORD"))."',
																name: 'usr_password',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: true,
																anchor:'100%'
															})]
													},{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("RE-TYPE_PASSWORD"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															inputType: 'password',
															fieldLabel: '".$this->db->escape_str($this->lang->line("RE-TYPE_PASSWORD"))."',
															name: 'usr_password_re',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: true,
															anchor:'100%'
														}]
													},{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("CONNECT_USER"))."',
														autoHeight:true,
														layout: {
															type: 'form'
														},
														items: [
															new Ext.Panel({
																layout: 'fit',
																border: true,
																html: '".$this->db->escape_str($this->lang->line("BY_CONNECTING_USER_AND_DATA_TYPE,_THE_USER_CAN_EDIT_THAT_DATA"))."',
																padding: 5,
																style: {marginBottom: '5px'}
															}),
															".((!Common::isAdmin())?("
															{
																xtype:'fieldset',
																title: '".$this->db->escape_str($this->lang->line("ORSZAGHOZ"))."',
																autoHeight:true,
																layout: {
																	type: 'anchor'
																},
																items: [{
																	xtype:'superboxselect',
																	fieldLabel: '".$this->db->escape_str($this->lang->line("ORSZAGHOZ"))."',
																	name:'cou_id[]',
																	renderFieldBtns: true,
																	anchor:'100%',
																	store: new Ext.data.ArrayStore({
																		fields: ['cou_id', 'cou_name'],
																		proxy : new Ext.data.HttpProxy({
																			url: '".site_url()."admin/get_country/obj',
																			method: 'GET'
																		}),
																		autoLoad: ".((isset($getUser[$this->input->post("id")]))?("true"):("false"))."
																	}),
																	".((isset($getUser[$this->input->post("id")]))?("value:'".$this->db->escape_str($getUser[$this->input->post("id")]["couList"])."',"):(""))."
																	mode: ".((isset($getUser[$this->input->post("id")]))?("'remote'"):("'local'")).",
																	triggerAction: 'all',
																	displayField: 'cou_name',
																	displayFieldTpl: '{cou_name}',
																	valueField: 'cou_id',
																	navigateItemsWithTab: false
																}]
															},
															{
																xtype:'fieldset',
																title: '".$this->db->escape_str($this->lang->line("FOR_CITY"))."',
																autoHeight:true,
																layout: {
																	type: 'anchor'
																},
																items: [{
																	xtype:'superboxselect',
																	fieldLabel: '".$this->db->escape_str($this->lang->line("FOR_CITY"))."',
																	name:'city_id[]',
																	renderFieldBtns: true,
																	anchor:'100%',
																	store: new Ext.data.ArrayStore({
																		fields: ['city_id', 'city_name', 'cou_name'],
																		proxy : new Ext.data.HttpProxy({
																			url: '".site_url()."admin/get_city/0/obj',
																			method: 'GET'
																		}),
																		autoLoad: ".((isset($getUser[$this->input->post("id")]))?("false"):("true"))."
																	}),
																	".((isset($getUser[$this->input->post("id")]))?("value:'".$this->db->escape_str($getUser[$this->input->post("id")]["cityList"])."',"):(""))."
																	mode: ".((isset($getUser[$this->input->post("id")]))?("'remote'"):("'local'")).",
																	triggerAction: 'all',
																	displayField: 'city_name',
																	tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{city_name} ({cou_name})</div></tpl>',
																	displayFieldTpl: '{city_name} ({cou_name})',
																	valueField: 'city_id',
																	minChars: 3,
																	allowQueryAll: true,
																	navigateItemsWithTab: false
																}]
															},"):(""))."
															{
																xtype:'fieldset',
																title: '".$this->db->escape_str($this->lang->line("TO_THE_INSTITUTE"))."',
																autoHeight:true,
																layout: {
																	type: 'anchor'
																},
																items: [{
																	xtype:'superboxselect',
																	fieldLabel: '".$this->db->escape_str($this->lang->line("TO_THE_INSTITUTE"))."',
																	name:'ins_id[]',
																	id:'ins_id',
																	renderFieldBtns: true,
																	anchor:'100%',
																	store: new Ext.data.ArrayStore({
																		fields: ['ins_id', 'ins_name', 'ins_url_name', 'city_id', 'insPriority', 'city_name'],
																		proxy : new Ext.data.HttpProxy({
																			url: '".site_url()."admin/get_institute/obj/type/0',
																			method: 'GET'
																		}),
																		autoLoad: ".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("false"):("true"))."
																	}),
																	".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("value:'".$this->db->escape_str((isset($getUser[$this->input->post("id")]))?($getUser[$this->input->post("id")]["insList"]):($adminUser["insList"]))."',"):(""))."
																	mode: ".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("'remote'"):("'local'")).",
																	triggerAction: 'all',
																	displayField: 'ins_name',
																	tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{ins_name} ({city_name})</div></tpl>',
																	displayFieldTpl: '{ins_name} ({city_name})',
																	valueField: 'ins_id',
																	minChars: 3,
																	navigateItemsWithTab: false
																}]
															}
														]
													},
													";
													/*
																												{
																xtype:'fieldset',
																title: '".$this->db->escape_str($this->lang->line("TO_PAGE_CATEGORY"))."',
																autoHeight:true,
																layout: {
																	type: 'anchor'
																},
																items: [{
																	xtype:'superboxselect',
																	fieldLabel: '".$this->db->escape_str($this->lang->line("TO_PAGE_CATEGORY"))."',
																	name:'page_cat[]',
																	id:'page_cat',
																	renderFieldBtns: true,
																	anchor:'100%',
																	store: new Ext.data.ArrayStore({
																		fields: ['szo_sname', 'szo_lname'],
																		proxy : new Ext.data.HttpProxy({
																			url: '".site_url()."admin/get_page_category',
																			method: 'GET'
																		}),
																		autoLoad: ".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("false"):("true"))."
																	}),
																	".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("value:'".$this->db->escape_str((isset($getUser[$this->input->post("id")]))?($getUser[$this->input->post("id")]["pageCatList"]):($adminUser["pageCatList"]))."',"):(""))."
																	mode: ".((isset($getUser[$this->input->post("id")]) or Common::isAdmin())?("'remote'"):("'local'")).",
																	triggerAction: 'all',
																	displayField: 'szo_lname',
																	valueField: 'szo_sname',
																	minChars: 3,
																	navigateItemsWithTab: false
																}]
															}
													*/
			} break;

			case "CON": {
				$this->load->model("continent");
				$getContinent = $this->continent->getContinent("con_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getContinent) {
					$windowTitle = $getContinent[0]["conName"];
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CONTINENT"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CONTINENT"))."',
															name: 'con_name',
															id: 'con_name',
															value: '".$this->db->escape_str($windowTitle)."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: true,
															listeners: {
																change: function (field, newValue) {
																	var geocoder = new google.maps.Geocoder();
																	geocoder.geocode( { address: field.getValue() }, function(results, status) {
																		if (status == google.maps.GeocoderStatus.OK) {
																			Ext.getCmp('con_latitude').setValue(results[0].geometry.location.lat());
																			Ext.getCmp('con_longitude').setValue(results[0].geometry.location.lng());
																		}
																	})
																}
															},
															anchor:'100%'
															}]
														},";
				}
			} break;
			case "COU": {
				$this->load->model("country");
				$getCountry = $this->country->getCountry("cou_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getCountry) {
					$windowTitle = $getCountry[0]["couName"];
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_COUNTRY"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_COUNTRY"))."',
															name: 'cou_name',
															id: 'cou_name',
															value: '".$this->db->escape_str($windowTitle)."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%',
															listeners: {
																change: function (field, newValue) {
																	var geocoder = new google.maps.Geocoder();
																	geocoder.geocode( { address: field.getValue() }, function(results, status) {
																		if (status == google.maps.GeocoderStatus.OK) {
																			Ext.getCmp('cou_latitude').setValue(results[0].geometry.location.lat());
																			Ext.getCmp('cou_longitude').setValue(results[0].geometry.location.lng());
																		}
																	})
																}
															}
															}]
														},
														";
				} else {
					//$this->load->model("continent");
					//$getContinent = $this->continent->getContinent("con_id = '".abs($this->db->escape_str($this->input->post("id")))."'");
					//if($getContinent) {
						//$windowTitle = $getContinent[0]["conName"];
						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_COUNTRY"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_COUNTRY"))."',
																name: 'cou_name',
																id: 'cou_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%',
																listeners: {
																	change: function (field, newValue) {
																		var geocoder = new google.maps.Geocoder();
																		geocoder.geocode( { address: field.getValue() }, function(results, status) {
																			if (status == google.maps.GeocoderStatus.OK) {
																				Ext.getCmp('cou_latitude').setValue(results[0].geometry.location.lat());
																				Ext.getCmp('cou_longitude').setValue(results[0].geometry.location.lng());
																			}
																		})
																	}
																}
																}]
															},
															";
					//}
				}

				$formElements .= "

														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("CONTINENT"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("CONTINENT"))."',
																hiddenName:'cou_con_id',
																store: new Ext.data.ArrayStore({
																	fields: ['con_id', 'con_name'],
																	url: '".site_url()."admin/getContinent',
																	autoLoad: true
																}),
																valueField:'con_id',
																displayField:'con_name',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getCountry[0]["couConId"]))?("hiddenValue: '".$this->db->escape_str($getCountry[0]["couConId"])."',"):(""))."
																".((isset($getCountry[0]["conName"]))?("value: '".$this->db->escape_str($getCountry[0]["conName"])."',"):(""))."
																anchor:'100%'
															})]
														}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP_DATA"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														tbar: [
															{
																icon: '".MEDIA."icon/zoom.png',
																text: '".$this->db->escape_str($this->lang->line("SEE_ON_MAP"))."',
																handler: function() {

																	mapwin = new Ext.Window({
																			layout: 'fit',
																			title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP"))."',
																			closeAction: 'hide',
																			width:400,
																			modal: true,
																			height:400,
																			items: {
																				xtype: 'gmappanel',
																				zoomLevel: 5,
																				gmapType: 'map',
																				mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
																				mapControls: ['GSmallMapControl','GMapTypeControl','NonExistantControl'],
																				setCenter: {
																					lat: Ext.getCmp('cou_latitude').getValue(),
																					lng: Ext.getCmp('cou_longitude').getValue(),
																					marker: {
																						lat: Ext.getCmp('cou_latitude').getValue(),
																						lng: Ext.getCmp('cou_longitude').getValue()
																					}
																				}
																			}
																	});
																	mapwin.show();

																}
															}
														],
														items: [{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
															name: 'cou_latitude',
															id: 'cou_latitude',
															".((isset($getCountry[0]))?("value: '".$this->db->escape_str($getCountry[0]["couLatitude"])."',"):(""))."
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															anchor:'100%'
															}]
														}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
															name: 'cou_longitude',
															id: 'cou_longitude',
															".((isset($getCountry[0]))?("value: '".$this->db->escape_str($getCountry[0]["couLongitude"])."',"):(""))."
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															anchor:'100%'
															}]
														}]
														},
													";

			} break;
			case "CITY": {
				$this->load->model("city");
				$getCity = $this->city->getCity("city_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getCity) {
					$windowTitle = $getCity[0]["cityName"];
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CITY"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CITY"))."',
															name: 'city_name',
															id: 'city_name',
															value: '".$this->db->escape_str($windowTitle)."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%',
															listeners: {
																change: function (field, newValue) {
																	var geocoder = new google.maps.Geocoder();
																	geocoder.geocode( { address: field.getValue() }, function(results, status) {
																		if (status == google.maps.GeocoderStatus.OK) {
																			Ext.getCmp('city_latitude').setValue(results[0].geometry.location.lat());
																			Ext.getCmp('city_longitude').setValue(results[0].geometry.location.lng());
																		}
																	})
																}
															}
															}]
														},
														";
				} else {
					//$this->load->model("country");
					//$getCountry = $this->country->getCountry("cou_id = '".abs($this->db->escape_str($this->input->post("id")))."'");
					//if($getCountry) {
						//$windowTitle = $getCountry[0]["couName"];
						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CITY"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'hidden',
																hidden: true,
																inputType: 'hidden',
																name: 'city_cou_id',
																value: '".abs($this->db->escape_str($this->input->post("id")))."'
																}, {
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_CITY"))."',
																name: 'city_name',
																id: 'city_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%',
																listeners: {
																	change: function (field, newValue) {
																		var geocoder = new google.maps.Geocoder();
																		geocoder.geocode( { address: field.getValue() }, function(results, status) {
																			if (status == google.maps.GeocoderStatus.OK) {
																				Ext.getCmp('city_latitude').setValue(results[0].geometry.location.lat());
																				Ext.getCmp('city_longitude').setValue(results[0].geometry.location.lng());
																			}
																		})
																	}
																}
																}]
															},
															";
					//}
				}

				$formElements .= "
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("COUNTRY"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("COUNTRY"))."',
																hiddenName:'city_cou_id',
																store: new Ext.data.ArrayStore({
																	fields: ['cou_id', 'cou_name'],
																	url: '".site_url()."admin/getCountry',
																	autoLoad: true
																}),
																valueField:'cou_id',
																displayField:'cou_name',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getCity[0]["cityCouId"]))?("hiddenValue: '".$this->db->escape_str($getCity[0]["cityCouId"])."',"):(""))."
																".((isset($getCity[0]["couName"]))?("value: '".$this->db->escape_str($getCity[0]["couName"])."',"):(""))."
																anchor:'100%'
															})]
														}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP_DATA"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														tbar: [
															{
																icon: '".MEDIA."icon/zoom.png',
																text: '".$this->db->escape_str($this->lang->line("SEE_ON_MAP"))."',
																handler: function() {

																	mapwin = new Ext.Window({
																			layout: 'fit',
																			title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP"))."',
																			closeAction: 'hide',
																			width:400,
																			modal: true,
																			height:400,
																			items: {
																				xtype: 'gmappanel',
																				zoomLevel: 10,
																				gmapType: 'map',
																				mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
																				mapControls: ['GSmallMapControl','GMapTypeControl','NonExistantControl'],
																				setCenter: {
																					lat: Ext.getCmp('city_latitude').getValue(),
																					lng: Ext.getCmp('city_longitude').getValue(),
																					marker: {
																						lat: Ext.getCmp('city_latitude').getValue(),
																						lng: Ext.getCmp('city_longitude').getValue()
																					}
																				}
																			}
																	});
																	mapwin.show();

																}
															}
														],
														items: [{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
															name: 'city_latitude',
															id: 'city_latitude',
															".((isset($getCity[0]))?("value: '".$this->db->escape_str($getCity[0]["cityLatitude"])."',"):(""))."
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															anchor:'100%'
															}]
														}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
															name: 'city_longitude',
															id: 'city_longitude',
															".((isset($getCity[0]))?("value: '".$this->db->escape_str($getCity[0]["cityLongitude"])."',"):(""))."
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															anchor:'100%'
															}]
														}]
														},
													";

			} break;
			case "FAC": {
				define("ENTITY", "FAC");
			}
			case "INS": {
				$this->load->model("institute");
				$getInstitute = $this->institute->getInstitute("ins_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getInstitute) {
					$windowTitle = $getInstitute[0]["insName"]." (".$getInstitute[0]["cityName"].")";
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
															name: 'ins_name',
															id: 'ins_name',
															value: '".$this->db->escape_str($getInstitute[0]["insName"])."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
															}]
														},
														";
				} else {
					if(Common::isAdmin() and $this->input->post("entity") == "INS" and $this->input->post("id") == -1) {
						$getCategoryVal = array();
						/*$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
																hiddenName:'ins_name',
																store: new Ext.data.ArrayStore({
																	fields: ['ins_id', 'ins_name', 'ins_url_name', 'ins_city_id', 'insPriority', 'city_name'],
																	url: '".site_url()."admin/getInstitute/1',
																	autoLoad: true
																}),
																valueField:'ins_name',
																displayField:'ins_name',
																tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{ins_name} ({city_name})</div></tpl>',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																editable: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
															})]
															},"; */
						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
																name: 'ins_name',
																".(($this->input->post("insName"))?("value: '".$this->db->escape_str($this->input->post("insName"))."',"):(""))."
																id: 'ins_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("ADDRESS"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("ADDRESS"))."',
																name: 'ins_address',
																id: 'ins_address',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															";
						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("WEBSITE"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("WEBSITE"))."',
																name: 'ins_website',
																id: 'ins_website',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															";
					} else {
						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_".(($this->input->post("entity") == "INS")?("INSTITUTE"):("FACULTY"))))."',
																name: 'ins_name',
																".(($this->input->post("insName"))?("value: '".$this->db->escape_str($this->input->post("insName"))."',"):(""))."
																id: 'ins_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															";
					}
				}

				if(!(Common::isAdmin() and $this->input->post("entity") == "INS" and $this->input->post("id") == -1)) {
				
					// új regisztrált
					if($this->input->post("insCityId")) {
						$this->load->model("city");
						$getCity = $this->city->getCity("city_id = '".intval($this->input->post("insCityId"))."'");
						if(count($getCity)) {
							$getInstitute[0]["insCityId"] = $getCity[0]["cityId"];
							$getInstitute[0]["cityName"] = $getCity[0]["cityName"];
						}
					}
				
					$formElements .= (($this->input->post("entity") == "FAC")?("
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("PARENT"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("PARENT"))."',
																hiddenName:'ins_ins_id',
																store: new Ext.data.ArrayStore({
																	fields: ['ins_id', 'ins_name', 'ins_url_name', 'ins_city_id', 'ins_priority', 'city_name', 'cou_name'],
																	url: '".site_url()."admin/get_institute/1/0/FAC/',
																	autoLoad: true
																}),
																valueField:'ins_id',
																displayField:'ins_name',
																tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{ins_name} ({city_name} - {cou_name})</div></tpl>',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getInstitute[0]["insInsId"]))?("hiddenValue: '".$this->db->escape_str($getInstitute[0]["insInsId"])."',"):(""))."
																".((isset($getInstitute[0]["parentInsName"]))?("value: '".$this->db->escape_str($getInstitute[0]["parentInsName"])."',"):(""))."
																anchor:'100%'
															})]
														},"):(""))."
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("CITY"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("CITY"))."',
																hiddenName:'ins_city_id',
																id: 'ins_city_id',
																store: new Ext.data.ArrayStore({
																	fields: ['city_id', 'city_name', 'city_url_name', 'city_cou_id', 'cou_name'],
																	url: '".site_url()."admin/getCity',
																	autoLoad: false
																}),
																valueField:'city_id',
																displayField:'city_name',
																tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{city_name} ({cou_name})</div></tpl>',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																minChars: 3,
																mode: 'remote',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getInstitute[0]["insCityId"]))?("hiddenValue: '".$this->db->escape_str($getInstitute[0]["insCityId"])."',"):(""))."
																".((isset($getInstitute[0]["cityName"]))?("value: '".$this->db->escape_str($getInstitute[0]["cityName"])."',"):(""))."
																anchor:'100%'
															})]
														},
														";
				}

			} break;
			case "ACC": {
				$this->load->model("accomodation");
				$getAccomodation = $this->accomodation->getAccomodation("acc_id = '".$this->db->escape_str($this->input->post("id"))."'");
				//Common::pr($getAccomodation );
				if($getAccomodation) {
					$windowTitle = $getAccomodation[0]["accName"]." (".$getAccomodation[0]["insNameList"].")";
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_ACCOMODATION"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_ACCOMODATION"))."',
															name: 'acc_name',
															id: 'acc_name',
															value: '".$this->db->escape_str($getAccomodation[0]["accName"])."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
															}]
														},
														";
				} else {
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_ACCOMODATION"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_THE_ACCOMODATION"))."',
															name: 'acc_name',
															".(($this->input->post("insName"))?("value: '".$this->db->escape_str($this->input->post("insName"))."',"):(""))."
															id: 'acc_name',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
															}]
														},
														";
				}

				$formElements .= 	"
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("INSTITUTE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype:'superboxselect',
															fieldLabel: '".$this->db->escape_str($this->lang->line("INSTITUTE"))."',
															name:'ins_id[]',
															id:'ins_id',
															renderFieldBtns: true,
															anchor:'100%',
															store: new Ext.data.ArrayStore({
																fields: ['ins_id', 'ins_name', 'ins_url_name', 'city_id', 'insPriority', 'city_name'],
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/get_institute/obj/false/ACC',
																	method: 'GET'
																}),
																autoLoad: ".((isset($getAccomodation[0]["insList"]))?("false"):("true"))."
															}),
															".((isset($getAccomodation[0]["insList"]))?("value: '".$this->db->escape_str($getAccomodation[0]["insList"])."',"):(""))."
															mode: ".((isset($getAccomodation[0]["insList"]))?("'remote'"):("'local'")).",
															triggerAction: 'all',
															displayField: 'ins_name',
															tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{ins_name} ({city_name})</div></tpl>',
															displayFieldTpl: '{ins_name} ({city_name})',
															valueField: 'ins_id',
															minChars: 3,
															navigateItemsWithTab: false
														}]
													},
													{
													xtype:'fieldset',
													title: '".$this->db->escape_str($this->lang->line("CITY"))."',
													autoHeight:true,
													layout: {
														type: 'anchor'
													},
													items: [
														new Ext.form.ComboBox({
															fieldLabel: '".$this->db->escape_str($this->lang->line("CITY"))."',
															hiddenName:'acc_city_id',
															id: 'acc_city_id',
															store: new Ext.data.ArrayStore({
																fields: ['city_id', 'city_name', 'city_url_name', 'city_cou_id', 'cou_name'],
																url: '".site_url()."admin/getCity',
																autoLoad: false
															}),
															valueField:'city_id',
															displayField:'city_name',
															tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{city_name} ({cou_name})</div></tpl>',
															editable: true,
															forceSelection: true,
															typeAhead: true,
															minChars: 3,
															mode: 'remote',
															triggerAction: 'all',
															emptyText:'...',
															selectOnFocus:true,
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															".((isset($getAccomodation[0]["accCityId"]))?("hiddenValue: '".$this->db->escape_str($getAccomodation[0]["accCityId"])."',"):(""))."
															".((isset($getAccomodation[0]["cityName"]))?("value: '".$this->db->escape_str($getAccomodation[0]["cityName"])."',"):(""))."
															anchor:'100%'
														})]
													},
													";

			} break;
			case "MAJ": {
				$this->load->model("major");
				$getMajor = $this->major->getMajor("maj_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getMajor) {
					$windowTitle = $getMajor[0]["majName"]." (".$getMajor[0]["insName"].")";
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("NAME_OF_COURSE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_COURSE"))."',
															name: 'maj_name',
															id: 'maj_name',
															value: '".$this->db->escape_str($getMajor[0]["majName"])."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
															}]
														},
														";
				} else {
					//$this->load->model("institute");
					//$getInstitute = $this->institute->getInstitute("ins_id = '".abs($this->db->escape_str($this->input->post("id")))."'");
					//if($getInstitute) {
						//$windowTitle = $getInstitute[0]["insName"];

						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("NAME_OF_COURSE"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("NAME_OF_COURSE"))."',
																name: 'maj_name',
																id: 'maj_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															";

					//}
				}
				$szotar = Common::szotar(array("PROGTYPE", "PROGTYPE_2"));
				$formElements .= "
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("PLEASE_CHOOSE_LISTING_INTERVAL"))."',
														autoHeight: true,
														anchor:'100%',
														layout: {
															type: 'anchor'
														},
														items: [
																{
																	xtype: 'compositefield',
																	items: [
																		{
																			xtype: 'datefield',
																			showToday: false,
																			format: '".$this->config->item("dateFormat")."',
																			fieldLabel: '',
																			name: 'maj_list_from_date',
																			value: '".((isset($getMajor[0]["majListFromDate"]))?(($this->db->escape_str($getMajor[0]["majListFromDate"]))):(""))."',
																			allowBlank: true,
																			anchor:'100%'
																		}, {
																			xtype: 'container',
																			html: ' - '
																		}, {
																			xtype: 'datefield',
																			showToday: false,
																			format: '".$this->config->item("dateFormat")."',
																			fieldLabel: '',
																			name: 'maj_list_till_date',
																			value: '".((isset($getMajor[0]["majListTillDate"]))?(($this->db->escape_str($getMajor[0]["majListTillDate"]))):(""))."',
																			allowBlank: true,
																			anchor:'100%'
																		}
																	]
																}
															]
													}
													,{
													xtype:'fieldset',
													title: '".$this->db->escape_str($this->lang->line("INSTITUTE"))."',
													autoHeight:true,
													layout: {
														type: 'anchor'
													},
													items: [
														new Ext.form.ComboBox({
															fieldLabel: '".$this->db->escape_str($this->lang->line("INSTITUTE"))."',
															hiddenName:'maj_ins_id',
															store: new Ext.data.ArrayStore({
																fields: ['ins_id', 'ins_name', 'ins_url_name', 'ins_city_id', 'insPriority', 'city_name'],
																url: '".site_url()."admin/getInstitute/MAJ',
																autoLoad: true
															}),
															valueField:'ins_id',
															displayField:'ins_name',
															tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{ins_name} ({city_name})</div></tpl>',
															editable: true,
															forceSelection: true,
															typeAhead: true,
															mode: 'local',
															triggerAction: 'all',
															emptyText:'...',
															listeners: {
																select: function(field, record, index) {
																	var newValue = field.getValue();
																	Ext.getCmp('acc_id').getStore().load({params: 'insId=' + newValue});
																	Ext.getCmp('acc_id').clearValue();
																	Ext.getCmp('acc_id').enable();
																}
															},
															selectOnFocus:true,
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															".((isset($getMajor[0]["majInsId"]))?("hiddenValue: '".$this->db->escape_str($getMajor[0]["majInsId"])."',"):(""))."
															".((isset($getMajor[0]["insName"]))?("value: '".$this->db->escape_str($getMajor[0]["insName"])."',"):(""))."
															anchor:'100%'
														})]
													}, 	{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("ACCOMODATION"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype:'superboxselect',
															fieldLabel: '".$this->db->escape_str($this->lang->line("ACCOMODATION"))."',
															name:'acc_id[]',
															id:'acc_id',
															renderFieldBtns: true,
															anchor:'100%',
															store: new Ext.data.ArrayStore({
																fields: ['acc_id', 'acc_name', 'acc_url_name', 'ins_list', 'ins_name_list', 'acc_city_id', 'city_name'],
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/get_accomodation/obj".((isset($getMajor[0]["majInsId"]))?("?insId=".intval($getMajor[0]["majInsId"])):(""))."',
																	method: 'GET'
																}),
																autoLoad: false
															}),
															".((isset($getMajor[0]["accList"]))?("value: '".$this->db->escape_str($getMajor[0]["accList"])."',"):(""))."
															mode: ".((isset($getMajor[0]["accList"]))?("'remote'"):("'local'")).",
															triggerAction: 'all',
															displayField: 'acc_name',
															tpl: '<tpl for=\".\"><div class=\"x-combo-list-item\">{acc_name} ({city_name})</div></tpl>',
															displayFieldTpl: '{acc_name} ({city_name})',
															valueField: 'acc_id',
															disabled: ".((isset($getMajor[0]["majInsId"]))?("false"):("true")).",
															minChars: 3,
															navigateItemsWithTab: false
														}]
													}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("SUBJECT_AREA_OF_THE_COURSE"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [
															new Ext.form.ComboBox({
																fieldLabel: '".$this->db->escape_str($this->lang->line("SUBJECT_AREA_OF_THE_COURSE"))."',
																hiddenName:'maj_sub_id',
																store: new Ext.data.ArrayStore({
																	fields: ['sub_id', 'sub_sub_id', 'group', 'sub_name'],
																	url: '".site_url()."admin/getSubject/full',
																	autoLoad: true
																}),
																tpl: new Ext.XTemplate(
																	'<tpl for=\".\">',
																	'<tpl if=\"this.group != values.group\">',
																	'<tpl exec=\"this.group = values.group\"></tpl>',
																	'<h1>{group}</h1>',
																	'</tpl>',
																	'<div class=\"x-combo-list-item\">{sub_name}</div>',
																	'</tpl>'
																),
																valueField:'sub_id',
																displayField:'sub_name',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																".((isset($getMajor[0]))?("
																	hiddenValue: '".$this->db->escape_str($getMajor[0]["subId"])."',
																	value: '".$this->db->escape_str($getMajor[0]["subName"])."',
																"):(""))."
																anchor:'100%'
															})]
														},
														{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("TYPE_OF_THE_COURSE"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [
																new Ext.form.ComboBox({
																	fieldLabel: '".$this->db->escape_str($this->lang->line("TYPE_OF_THE_COURSE"))."',
																	hiddenName:'maj_prog_type',
																	id:'frmMajProgType',
																	store: new Ext.data.ArrayStore({
																		fields: ['prog_type_sname', 'prog_type_lname'],
																		data : ".Common::arr2jsobj($szotar["PROGTYPE"])."
																	}),
																	listeners: {
																		select: function(field, record, index) {

																			var value = Ext.getCmp('frmMajProgType2').getValue();

																			Ext.getCmp('frmMajProgType2').getStore().load({params: {
																				'progType': field.getValue()
																			},
																			callback: function(r,options,success){
																				if (success) {
																					if(Ext.getCmp('frmMajProgType2').getStore().find('prog_type_sname', value, false) == -1) {
																						Ext.getCmp('frmMajProgType2').setValue('');
																					} else {
																						Ext.getCmp('frmMajProgType2').setValue(value);
																					}
																				}
																			}
																				});

																		}
																	},
																	valueField:'prog_type_sname',
																	displayField:'prog_type_lname',
																	editable: true,
																	forceSelection: true,
																	typeAhead: true,
																	mode: 'local',
																	triggerAction: 'all',
																	emptyText:'...',
																	selectOnFocus:true,
																	allowBlank: false,
																	blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																	".((isset($getMajor[0]))?("
																		hiddenValue: '".$this->db->escape_str($getMajor[0]["majProgType"])."',
																		value: '".$this->db->escape_str($getMajor[0]["majProgTypeLname"])."',
																	"):(""))."
																	anchor:'100%'
																})
															]
														}, {
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("PROGRAM_TYPE"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [
																new Ext.form.ComboBox({
																	fieldLabel: '".$this->db->escape_str($this->lang->line("PROGRAM_TYPE"))."',
																	hiddenName:'maj_prog_type2',
																	id:'frmMajProgType2',
																	store: new Ext.data.ArrayStore({

																		fields: ['prog_type_sname', 'prog_type_lname'],
																		url: '".site_url()."admin/getSzotar/PROGTYPE_2/".((isset($getMajor[0]["majProgType"]))?($getMajor[0]["majProgType"]):(""))."',
																		autoLoad: true,

																		listeners: {
																			".((isset($getMajor[0]["majProgType2"]))?("
																			load: function() {
																				Ext.getCmp('frmMajProgType2').setValue('".$this->db->escape_str($getMajor[0]["majProgType2"])."');
																			}
																			"):(""))."
																		}

																		//fields: ['prog_type_sname', 'prog_type_lname'],
																		//data : ".Common::arr2jsobj(array("" => "...") + $szotar["PROGTYPE_2"])."

																	}),
																	valueField:'prog_type_sname',
																	displayField:'prog_type_lname',
																	editable: true,
																	forceSelection: true,
																	typeAhead: true,
																	mode: 'local',
																	triggerAction: 'all',
																	emptyText:'...',
																	selectOnFocus:true,
																	allowBlank: false,
																	blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																	".((isset($getMajor[0]))?("
																		hiddenValue: '".$this->db->escape_str($getMajor[0]["majProgType2"])."',
																		value: '".$this->db->escape_str($getMajor[0]["majProgType2Lname"])."',
																	"):(""))."
																	anchor:'100%'
																})
															]
														},";

			} break;
			
			case "SCH": {
				$this->load->model("scholarship");
				$getScholarship = $this->scholarship->getScholarship("sch_id = '".$this->db->escape_str($this->input->post("id"))."'");
				if($getScholarship) {
					$windowTitle = $getScholarship[0]["schName"]." (".$getScholarship[0]["schName"].")";
					$formElements .=	"
														{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("SCHOLARSHIP_NAME"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'textfield',
															fieldLabel: '".$this->db->escape_str($this->lang->line("SCHOLARSHIP_NAME"))."',
															name: 'sch_name',
															id: 'sch_name',
															value: '".$this->db->escape_str($getScholarship[0]["schName"])."',
															maxLength: 255,
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															allowBlank: false,
															blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
															anchor:'100%'
															}]
														},
														";
				} else {
					//$this->load->model("institute");
					//$getInstitute = $this->institute->getInstitute("ins_id = '".abs($this->db->escape_str($this->input->post("id")))."'");
					//if($getInstitute) {
						//$windowTitle = $getInstitute[0]["insName"];

						$formElements .=	"
															{
															xtype:'fieldset',
															title: '".$this->db->escape_str($this->lang->line("SCHOLARSHIP_NAME"))."',
															autoHeight:true,
															layout: {
																type: 'anchor'
															},
															items: [{
																xtype: 'textfield',
																fieldLabel: '".$this->db->escape_str($this->lang->line("SCHOLARSHIP_NAME"))."',
																name: 'sch_name',
																id: 'sch_name',
																maxLength: 255,
																maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																anchor:'100%'
																}]
															},
															";

					//}
				}

				$formElements .= "
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("LIST_BY"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [{
															xtype: 'datefield',
															showToday: false,
															format: '".$this->config->item("dateFormat")."',
															fieldLabel: '".$this->db->escape_str($this->lang->line("LIST_BY"))."',
															name: 'sch_list_date',
															value: '".((isset($getScholarship[0]["schListDate"]))?(Common::dateFromDatabase($this->db->escape_str($getScholarship[0]["schListDate"]))):(""))."',
															allowBlank: true,
															anchor:'100%'
														}]
													},
													{
													xtype:'fieldset',
													title: '".$this->db->escape_str($this->lang->line("TO_THE_INSTITUTE"))."',
													autoHeight:true,
													layout: {
														type: 'anchor'
													},
													items: [{
															xtype:'superboxselect',
															fieldLabel: '".$this->db->escape_str($this->lang->line("TO_THE_INSTITUTE"))."',
															name:'ins_id[]',
															renderFieldBtns: true,
															anchor:'100%',
															store: new Ext.data.ArrayStore({
																fields: ['ins_id', 'ins_name'],
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/get_institute/obj/false/SCH',
																	method: 'GET'
																}),
																autoLoad: ".((!isset($getScholarship[0]["insList"]))?("true"):("false"))."
															}),
															".((isset($getScholarship[0]["insList"]))?("value:'".$this->db->escape_str($getScholarship[0]["insList"])."',"):(""))."
															mode: ".((isset($getScholarship[0]["insList"]))?("'remote'"):("'local'")).",
															triggerAction: 'all',
															displayField: 'ins_name',
															displayFieldTpl: '{ins_name}',
															valueField: 'ins_id',
															navigateItemsWithTab: false
														}]
													}, {
													xtype:'fieldset',
													title: '".$this->db->escape_str($this->lang->line("TO_THE_MAJOR"))."',
													autoHeight:true,
													layout: {
														type: 'anchor'
													},
													items: [{
															xtype:'superboxselect',
															fieldLabel: '".$this->db->escape_str($this->lang->line("TO_THE_MAJOR"))."',
															name:'maj_id[]',
															renderFieldBtns: true,
															anchor:'100%',
															store: new Ext.data.ArrayStore({
																fields: ['maj_id', 'maj_name', 'maj_url_name', 'maj_ins_name', 'ins_name'],
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/get_major/false/obj',
																	method: 'GET'
																}),
																autoLoad: ".((!isset($getScholarship[0]["majList"]))?("true"):("false"))."
															}),
															".((isset($getScholarship[0]["majList"]))?("value:'".$this->db->escape_str($getScholarship[0]["majList"])."',"):(""))."
															mode: ".((isset($getScholarship[0]))?("'remote'"):("'local'")).",
															triggerAction: 'all',
															displayField: 'maj_name',
															displayFieldTpl: '{maj_name} ({ins_name})',
															valueField: 'maj_id',
															navigateItemsWithTab: false
														}]
													}, {
													xtype:'fieldset',
													title: '".$this->db->escape_str($this->lang->line("CANDIDATE_MUST_BE_FROM"))."',
													autoHeight:true,
													layout: {
														type: 'anchor'
													},
													items: [{
															xtype:'superboxselect',
															fieldLabel: '".$this->db->escape_str($this->lang->line("CANDIDATE_MUST_BE_FROM"))."',
															name:'cou_id[]',
															renderFieldBtns: true,
															anchor:'100%',
															store: new Ext.data.ArrayStore({
																fields: ['cou_id', 'cou_name'],
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/getCountry/obj',
																	method: 'GET'
																}),
																autoLoad: ".((!isset($getScholarship[0]["couList"]))?("true"):("false"))."
															}),
															".((isset($getScholarship[0]["couList"]))?("value:'".$this->db->escape_str($getScholarship[0]["couList"])."',"):(""))."
															mode: ".((isset($getScholarship[0]))?("'remote'"):("'local'")).",
															triggerAction: 'all',
															displayField: 'cou_name',
															displayFieldTpl: '{cou_name}',
															valueField: 'cou_id',
															navigateItemsWithTab: false
														}]
													}, {
														xtype:'fieldset',
														title: '".$this->db->escape_str($this->lang->line("STUDYING"))."',
														autoHeight:true,
														layout: {
															type: 'anchor'
														},
														items: [ new Ext.form.ComboBox({
															fieldLabel: '".$this->db->escape_str($this->lang->line("STUDYING"))."',
															hiddenName:'sch_sub_id',
															store: new Ext.data.ArrayStore({
																fields: ['sub_id', 'sub_sub_id', 'group', 'sub_name'],
																autoLoad: true,
																proxy : new Ext.data.HttpProxy({
																	url: '".site_url()."admin/getSubject/full',
																	method: 'GET'
																}),
															}),
															valueField:'sub_id',
															displayField:'sub_name',
															editable: false,
															tpl: new Ext.XTemplate(
																'<tpl for=\".\">',
																'<tpl if=\"this.group != values.group\">',
																'<tpl exec=\"this.group = values.group\"></tpl>',
																'<h1>{group}</h1>',
																'</tpl>',
																'<div class=\"x-combo-list-item\">{sub_name}</div>',
																'</tpl>'
															),
															mode: 'local',
															triggerAction: 'all',
															emptyText:'...',
															selectOnFocus:true,
															allowBlank: true,
															".((isset($getScholarship[0]["schSubId"]) and $getScholarship[0]["schSubId"])?("hiddenValue: '".$this->db->escape_str($getScholarship[0]["schSubId"])."', value: '".$this->db->escape_str($getScholarship[0]["schSubName"])."',"):(""))."
															anchor:'100%'
															})
														] 
													},";


			} break;
			
		}
		//Common::pr($getCategoryVal);
		if(count($getCategoryVal) or true) {

			echo	"var formCategories = new Array();";

			foreach($getCategoryVal as $catId => $catData) {
				
				// uj intezmeny rögzítésénél insName, insAddress, insWweb
				if($this->input->post("id") == -1) {
					if($catId == $this->config->item("categoryINSAddress")) {
						$catData["val"] = $this->input->post("insAddress");
					}
					if($catId == $this->config->item("categoryINSWeb")) {
						$catData["val"] = $this->input->post("insWeb");
					}
					if($catId == $this->config->item("categoryINSPostalCode")) {
						$catData["val"] = $this->input->post("insPostalCode");
					}
				}
				
				// SCH Amount
				if($catId == $this->config->item("categorySCHAmountId")) {
				
					echo	"
							formCategories.push({
												xtype: 'compositefield',
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												items: [
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($catData["catName"])."',
														autoHeight:true,
														anchor: '100%',
														layout: {
															type: 'table'
														},
														items: [{
															xtype: 'numberfield',
															allowDecimals: false,
															fieldLabel: '".$this->db->escape_str($catData["catName"])."',
															name: 'cat_".$catId."',
															id: 'cat_".$catId."',
															".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															value: '".$this->db->escape_str($catData["val"])."',
															allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
															anchor:'100%'
															}
															".((isset($getCategoryVal[$this->config->item("categorySCHAmountCurrencyId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;'}, {
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountCurrencyId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categorySCHAmountCurrencyId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['curr_id', 'curr_text', 'curr_order'],
																	url: '".site_url()."admin/getCurrency',
																	autoLoad: true
																}),
																valueField:'curr_text',
																displayField:'curr_text',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountCurrencyId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categorySCHAmountCurrencyId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountCurrencyId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															".((isset($getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;/&nbsp;&nbsp;'},{
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categorySCHAmountIntervalId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['cat_id', 'cat_name'],
																	url: '".site_url()."admin/getCatList/".$getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]["catList"]."',
																	autoLoad: true
																}),
																valueField:'cat_name',
																displayField:'cat_name',
																triggerAction: 'all',
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categorySCHAmountIntervalId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															]
													}
												]
												});
							";
				
				} elseif(in_array($catId, array($this->config->item("categorySCHAmountCurrencyId"), $this->config->item("categorySCHAmountIntervalId")))) { // SCH Amount composite elemek kihagyása
					continue;
				} elseif($catId == $this->config->item("categoryACCFeeId")) { // Accomodation
				
					echo	"
							formCategories.push({
												xtype: 'compositefield',
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												items: [
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($catData["catName"])."',
														autoHeight:true,
														anchor: '100%',
														layout: {
															type: 'table'
														},
														items: [{
															xtype: 'numberfield',
															allowDecimals: false,
															fieldLabel: '".$this->db->escape_str($catData["catName"])."',
															name: 'cat_".$catId."',
															id: 'cat_".$catId."',
															".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															value: '".$this->db->escape_str($catData["val"])."',
															allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
															anchor:'100%'
															}
															".((isset($getCategoryVal[$this->config->item("categoryACCFeeCurrencyId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;'}, {
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeCurrencyId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categoryACCFeeCurrencyId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['curr_id', 'curr_text', 'curr_order'],
																	url: '".site_url()."admin/getCurrency',
																	autoLoad: true
																}),
																valueField:'curr_text',
																displayField:'curr_text',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeCurrencyId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categoryACCFeeCurrencyId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeCurrencyId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															".((isset($getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;/&nbsp;&nbsp;'},{
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categoryACCFeeIntervalId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['cat_id', 'cat_name'],
																	url: '".site_url()."admin/getCatList/".$getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]["catList"]."',
																	autoLoad: true
																}),
																valueField:'cat_name',
																displayField:'cat_name',
																triggerAction: 'all',
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryACCFeeIntervalId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															]
													}
												]
												});
							";
				
				} elseif(in_array($catId, array($this->config->item("categoryACCFeeCurrencyId"), $this->config->item("categoryACCFeeIntervalId")))) { // ACC Amount composite elemek kihagyása
					continue;
				} elseif($catId == $this->config->item("categoryMAJFeeId")) { // MAJ Fee
					echo	"
							formCategories.push({
												xtype: 'compositefield',
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												items: [
													{
														xtype:'fieldset',
														title: '".$this->db->escape_str($catData["catName"])."',
														autoHeight:true,
														anchor: '100%',
														layout: {
															type: 'table'
														},
														items: [{
															xtype: 'numberfield',
															allowDecimals: false,
															fieldLabel: '".$this->db->escape_str($catData["catName"])."',
															name: 'cat_".$catId."',
															id: 'cat_".$catId."',
															".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
															maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
															value: '".$this->db->escape_str($catData["val"])."',
															allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
															anchor:'100%'
															}
															".((isset($getCategoryVal[$this->config->item("categoryMAJFeeCurrencyId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;'}, {
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeCurrencyId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categoryMAJFeeCurrencyId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['curr_id', 'curr_text', 'curr_order'],
																	url: '".site_url()."admin/getCurrency',
																	autoLoad: true
																}),
																valueField:'curr_text',
																displayField:'curr_text',
																editable: true,
																forceSelection: true,
																typeAhead: true,
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																allowBlank: false,
																blankText: '".$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))."',
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeCurrencyId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categoryMAJFeeCurrencyId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeCurrencyId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															".((isset($getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]))?("
															,{xtype: 'container', html: '&nbsp;&nbsp;/&nbsp;&nbsp;'},{
																xtype: 'combo',
																fieldLabel: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]["catName"])."',
																hiddenName: 'cat_".$this->config->item("categoryMAJFeeIntervalId")."',
																store: new Ext.data.ArrayStore({
																	fields: ['cat_id', 'cat_name'],
																	url: '".site_url()."admin/getCatList/".$getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]["catList"]."',
																	autoLoad: true
																}),
																valueField:'cat_name',
																displayField:'cat_name',
																triggerAction: 'all',
																mode: 'local',
																triggerAction: 'all',
																emptyText:'...',
																selectOnFocus:true,
																hiddenValue: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]["val"])."',
																allowBlank: ".(($getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]["catRequired"] == "I")?("false"):("true")).",
																value: '".$this->db->escape_str($getCategoryVal[$this->config->item("categoryMAJFeeIntervalId")]["val"])."',
																anchor:'100%'
															}
															"):(""))."
															]
													}
												]
												});
							";
				} elseif(in_array($catId, array($this->config->item("categoryMAJFeeCurrencyId"), $this->config->item("categoryMAJFeeIntervalId")))) { // MAJ Fee composite elemek kihagyása
					continue;
				} else {
				
					switch($catData["catType"]) {
						case 'I': {
							echo	"
										formCategories.push({
											xtype:'fieldset',
											title: '".$this->db->escape_str($catData["catName"])."',
											autoHeight:true,
											layout: {
												type: 'anchor'
											},
											items: [{
												xtype: 'numberfield',
												allowDecimals: false,
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												name: 'cat_".$catId."',
												id: 'cat_".$catId."',
												".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
												maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
												value: '".$this->db->escape_str($catData["val"])."',
												allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
												anchor:'100%'
											}]
										});
										";
						} break;
						case 'D': {
							echo	"
										formCategories.push({
											xtype:'fieldset',
											title: '".$this->db->escape_str($catData["catName"])."',
											autoHeight:true,
											layout: {
												type: 'anchor'
											},
											items: [{
												xtype: 'datefield',
												showToday: false,
												format: '".$this->config->item("dateFormat")."',
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												name: 'cat_".$catId."',
												id: 'cat_".$catId."',
												value: '".$this->db->escape_str($catData["val"])."',
												allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
												anchor:'100%'
											}]
										});
										";
										
										/*
							echo	"
										formCategories.push({
											xtype: 'compositefield',
											fieldLabel: '".$this->db->escape_str($catData["catName"])." (dd/mm/yyyy)',
											items: [
												{
													xtype:'fieldset',
													title: '".$this->db->escape_str($catData["catName"])." (mm/dd/yyyy)',
													autoHeight:true,
													anchor: '100%',
													width: 300,
													layout: {
														type: 'table'
													},
													items: [{
														xtype: 'numberfield',
														allowDecimals: false,
														fieldLabel: '".$this->db->escape_str($catData["catName"])."',
														name: 'cat_".$catId."_month',
														id: 'cat_".$catId."_month',
														maxLength: 2,
														maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
														value: '".$this->db->escape_str(Common::dateFromCategory("m", $catData["val"]))."',
														allowBlank: true,
														autoCreate: {tag: 'input', type: 'text', size: '3', autocomplete: 'off', maxlength: '2'},
														width: 30
														},
														{xtype: 'container', html: '&nbsp;.&nbsp;'},
														{
														xtype: 'numberfield',
														allowDecimals: false,
														fieldLabel: '".$this->db->escape_str($catData["catName"])."',
														name: 'cat_".$catId."_day',
														id: 'cat_".$catId."_day',
														maxLength: 2,
														maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
														value: '".$this->db->escape_str(Common::dateFromCategory("d", $catData["val"]))."',
														allowBlank: true,
														autoCreate: {tag: 'input', type: 'text', size: '3', autocomplete: 'off', maxlength: '2'},
														width: 30
														},
														{xtype: 'container', html: '&nbsp;.&nbsp;'},
														{
														xtype: 'numberfield',
														allowDecimals: false,
														fieldLabel: '".$this->db->escape_str($catData["catName"])."',
														name: 'cat_".$catId."_year',
														id: 'cat_".$catId."_year',
														maxLength: 4,
														maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
														value: '".$this->db->escape_str(Common::dateFromCategory("y", $catData["val"]))."',
														allowBlank: true,
														autoCreate: {tag: 'input', type: 'text', size: '5', autocomplete: 'off', maxlength: '4'},
														width: 50
														}
														]
												}
											]
											})";
											*/
						} break;
						case 'T': {
							echo	"
										formCategories.push({
											xtype:'fieldset',
											title: '".$this->db->escape_str($catData["catName"])."',
											autoHeight:true,
											layout: {
												type: 'anchor'
											},
											items: [{
												xtype: 'panel',
												border: false,
												html: '<textarea name=\"cat_".$catId."\" id=\"cat_".$catId."\" rows=\"10\"></textarea>'
											}]
										})
										";
							$ckEditor = ((isset($ckEditor))?($ckEditor):(""))."
										CKEDITOR.replace('cat_".$catId."', {
											on :{
												instanceReady : function() {
													this.setData('".$this->db->escape_str($catData["val"])."');
												}
											}
										});
										";
							$ckEditorSave = ((isset($ckEditorSave))?($ckEditorSave):(""))."$('#cat_".$catId."').val(CKEDITOR.instances.cat_".$catId.".getData());";
						} break; 

						/*
						case 'TDEPRECATED': {
							echo	"
										formCategories.push({
											xtype:'fieldset',
											title: '".$this->db->escape_str($catData["catName"])."',
											autoHeight:true,
											layout: {
												type: 'anchor'
											},
											items: [{
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												xtype: 'htmleditor',
												allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
												enableColors: true,
												enableLinks: true,
												enableFont: false,
												".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
												maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
												enableSourceEdit: true,
												name: 'cat_".$catId."',
												id: 'cat_".$catId."',
												anchor:'100%',
												height: 160,
												value: '".$this->db->escape_str($catData["val"])."',
												listeners: {
													render: function(editor) {
														editor.getToolbar().insertButton(editor.getToolbar().items.length, {
															iconCls: 'upload-icon',
															handler: function(b,e) {
																Ext.Msg.prompt('Insert Image', 'Image URL', function(btn, txt) {
																	if (btn == 'ok') {
																		editor.relayCmd('insertimage', txt);
																	}
																});                                            
															}
														});
													}
												}
												
											}]
										})
										";
						} break; 
						*/
						case 'C': {
							echo	"
										formCategories.push({
											xtype:'fieldset',
											title: '".$this->db->escape_str($catData["catName"])."',
											autoHeight:true,
											layout: {
												type: 'anchor'
											},
											items: [{
												xtype: 'textfield',
												fieldLabel: '".$this->db->escape_str($catData["catName"])."',
												name: 'cat_".$catId."',
												id: 'cat_".$catId."',
												value: '".$this->db->escape_str($catData["val"])."',
												".((($catData["catLength"]))?("maxLength: ".$catData["catLength"].","):(""))."
												maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
												allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
												anchor:'100%'";

							if(($this->input->post("entity") == "INS" and $catId == $this->config->item("categoryINSAddress")) or ($this->input->post("entity") == "FAC" and $catId == $this->config->item("categoryFACAddress"))) {
								echo	"
											,listeners: {
											change: function (field, newValue) {
												var geocoder = new google.maps.Geocoder();
												geocoder.geocode( { address: Ext.getCmp('ins_city_id').getValue() + ', ' + ((Ext.getCmp('cat_".$this->config->item("categoryINSPostalCode")."'))?(Ext.getCmp('cat_".$this->config->item("categoryINSPostalCode")."').getValue() + ' '):('')) + field.getValue() }, function(results, status) {
													if (status == google.maps.GeocoderStatus.OK) {
														Ext.getCmp('ins_latitude').setValue(results[0].geometry.location.lat());
														Ext.getCmp('ins_longitude').setValue(results[0].geometry.location.lng());
													}
												})
											}
										}
											";
							}
							if($this->input->post("entity") == "ACC" and $catId == $this->config->item("categoryACCAddress")) {
								echo	"
											,listeners: {
											change: function (field, newValue) {
												var geocoder = new google.maps.Geocoder();
												geocoder.geocode( { address: Ext.getCmp('acc_city_id').getValue() + ', ' + ((Ext.getCmp('cat_".$this->config->item("categoryACCPostalCode")."'))?(Ext.getCmp('cat_".$this->config->item("categoryACCPostalCode")."').getValue() + ' '):('')) + field.getValue() }, function(results, status) {
													if (status == google.maps.GeocoderStatus.OK) {
														Ext.getCmp('acc_latitude').setValue(results[0].geometry.location.lat());
														Ext.getCmp('acc_longitude').setValue(results[0].geometry.location.lng());
													}
												})
											}
										}
											";
							}
							echo	"
											}]
										});
										";
						} break;
						case 'L': {
							if(json_decode($catData["catList"])) {
								$catList = json_decode($catData["catList"]);
								$data = "";
								foreach($catList as $groupName => $groupData) {
									foreach($groupData as $subName) {
										$data .= (($data)?(","):("")) . "[\"".$groupName."\", \"".$subName."\"]";
									}
								}
								$data = "[".$data."]";
								echo	"
											formCategories.push({
												xtype:'fieldset',
												title: '".$this->db->escape_str($catData["catName"])."',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													xtype: 'combo',
													fieldLabel: '".$this->db->escape_str($catData["catName"])."',
													hiddenName: 'cat_".$catId."',
													store: new Ext.data.ArrayStore({
														fields: ['group_name', 'sub_name'],
														data: ".$data.",
														autoLoad: true
													}),
													tpl: new Ext.XTemplate(
														'<tpl for=\".\">',
														'<tpl if=\"this.group_name != values.group_name\">',
														'<tpl exec=\"this.group_name = values.group_name\"></tpl>',
														'<h1>{group_name}</h1>',
														'</tpl>',
														'<div class=\"x-combo-list-item\">{sub_name}</div>',
														'</tpl>'
													),
													valueField:'sub_name',
													displayField:'sub_name',
													triggerAction: 'all',
													mode: 'local',
													triggerAction: 'all',
													emptyText:'...',
													selectOnFocus:true,
													hiddenValue: '".$this->db->escape_str($catData["val"])."',
													allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
													value: '".$this->db->escape_str($catData["val"])."',
													anchor:'100%'
												}]
											})
											";
							} else {
								echo	"
											formCategories.push({
												xtype:'fieldset',
												title: '".$this->db->escape_str($catData["catName"])."',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													xtype: 'combo',
													fieldLabel: '".$this->db->escape_str($catData["catName"])."',
													hiddenName: 'cat_".$catId."',
													store: new Ext.data.ArrayStore({
														fields: ['cat_id', 'cat_name'],
														url: '".site_url()."admin/getCatList/".$catData["catList"]."',
														autoLoad: true
													}),
													valueField:'cat_name',
													displayField:'cat_name',
													triggerAction: 'all',
													mode: 'local',
													triggerAction: 'all',
													emptyText:'...',
													selectOnFocus:true,
													hiddenValue: '".$this->db->escape_str($catData["val"])."',
													allowBlank: ".(($catData["catRequired"] == "I")?("false"):("true")).",
													value: '".$this->db->escape_str($catData["val"])."',
													anchor:'100%'
												}]
											})
											";
							}
						}  break;
					}
					
				}

				if((($this->input->post("entity") == "INS" and $catId == $this->config->item("categoryINSAddress")) or ($this->input->post("entity") == "FAC" and $catId == $this->config->item("categoryFACAddress")) or ($this->input->post("entity") == "ACC" and $catId == $this->config->item("categoryACCAddress")))) {

					echo	"
							formCategories.push({
								xtype:'fieldset',
								title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP_DATA"))."',
								autoHeight:true,
								layout: {
									type: 'anchor'
								},
								tbar: [
									{
										icon: '".MEDIA."icon/zoom.png',
										text: '".$this->db->escape_str($this->lang->line("SEE_ON_MAP"))."',
										handler: function() {

											mapwin = new Ext.Window({
													layout: 'fit',
													title: '".$this->db->escape_str($this->lang->line("GOOGLE_MAP"))."',
													closeAction: 'hide',
													width:400,
													modal: true,
													height:400,
													items: {
														xtype: 'gmappanel',
														zoomLevel: 15,
														gmapType: 'map',
														mapConfOpts: ['enableScrollWheelZoom','enableDoubleClickZoom','enableDragging'],
														mapControls: ['GSmallMapControl','GMapTypeControl','NonExistantControl'],
														setCenter: {
															lat: Ext.getCmp('".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_latitude').getValue(),
															lng: Ext.getCmp('".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_longitude').getValue(),
															marker: {
																lat: Ext.getCmp('".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_latitude').getValue(),
																lng: Ext.getCmp('".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_longitude').getValue()
															}
														}
													}
											});
											mapwin.show();

										}
									}
								],
								items: [{
								xtype:'fieldset',
								title: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
								autoHeight:true,
								layout: {
									type: 'anchor'
								},
								items: [{
									xtype: 'textfield',
									fieldLabel: '".$this->db->escape_str($this->lang->line("LATITUDE"))."',
									name: '".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_latitude',
									id: '".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_latitude',
									".((isset($getInstitute[0]["insLatitude"]))?("value: '".$this->db->escape_str($getInstitute[0]["insLatitude"])."',"):(""))."
									".((isset($getAccomodation[0]["accLatitude"]))?("value: '".$this->db->escape_str($getAccomodation[0]["accLatitude"])."',"):(""))."
									maxLength: 255,
									maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
									anchor:'100%'
									}]
								}, {
								xtype:'fieldset',
								title: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
								autoHeight:true,
								layout: {
									type: 'anchor'
								},
								items: [{
									xtype: 'textfield',
									fieldLabel: '".$this->db->escape_str($this->lang->line("LONGITUDE"))."',
									name: '".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_longitude',
									id: '".(($this->input->post("entity") == "ACC")?("acc"):("ins"))."_longitude',
									".((isset($getInstitute[0]["insLongitude"]))?("value: '".$this->db->escape_str($getInstitute[0]["insLongitude"])."',"):(""))."
									".((isset($getAccomodation[0]["accLongitude"]))?("value: '".$this->db->escape_str($getAccomodation[0]["accLongitude"])."',"):(""))."
									maxLength: 255,
									maxLengthText: '".$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))."',
									anchor:'100%'
									}]
								}]
								})
							";

				}

			}

			/* close listener window
									//Ext.getCmp('treeGrid').getUpdater().update({url:'".site_url()."admin/getContinentList/".$this->input->post("entity")."/".$this->input->get_post("id")."'})
									//Ext.getCmp('treeGrid').getRootNode().reload();
									//if(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid')) Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').getStore().reload(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').lastOptions);
									//if(Ext.getCmp('userGrid')) Ext.getCmp('userGrid').getStore().reload(Ext.getCmp('userGrid').lastOptions);
			*/
			
			// administrators panel
			if(intval($this->input->post("id")) > 0) {
				$strUserList = "<h3>".$this->lang->line("ADMINISTRATORS")."</h3>";
				$where = NULL;
				$this->load->model("usr2ent");
				switch($this->input->post("entity")) {
					case "CON": {
						$where = "1 = 2";
					} break;
					case "COU": {
						$where = "u2e_cou_id = '".intval($this->input->post("id"))."'";
					} break;
					case "CITY": {
						$where = "u2e_city_id = '".intval($this->input->post("id"))."'";
					} break;
					case "INS": {
						$where = "u2e_ins_id = '".intval($this->input->post("id"))."' and u2e_page_cat = 'IMP'";
					} break;
					case "MAJ": {
						$ID = ((isset($getMajor[0]["majInsId"]))?($getMajor[0]["majInsId"]):(0));
						$where = "u2e_ins_id = '".intval($this->input->post("id"))."' and u2e_page_cat = 'MAJ'";
					} break;
					case "SCH": {
						$IDs = ((isset($getScholarship[0]["INS"]))?(implode(", ", array_keys($getScholarship[0]["INS"]))):(0));
						$where = "u2e_ins_id in ('".$IDs."') and u2e_page_cat = 'SCH'";
					} break;
					case "ACC": {
						$IDs = ((isset($getAccomodation[0]["insList"]))?($getAccomodation[0]["insList"]):(0));
						$where = "u2e_ins_id in ('".$IDs."') and u2e_page_cat = 'ACC'";
					} break;
					case "FAC": {
						$where = "u2e_ins_id = '".intval($this->input->post("id"))."' and u2e_page_cat = 'FAC'";
					} break;
				}
				$getUserList2Ent = $this->usr2ent->getUserList2Ent($where);
				if(count($getUserList2Ent)) {
					foreach($getUserList2Ent as $ii => $usr) {
						$strUserList .= (($ii)?("<br/>"):("")) . $usr;
					}
				} else {
					$strUserList .= $this->lang->line("CURRENTLY_THERE_ARE_NO_ADMINISTRATORS_AVAILABLE");
				}
				
				$this->load->model("ent2cat");
				$getEnt2cat = $this->ent2cat->getEnt2cat($where = "e2c_entity = '".$this->db->escape_str($this->input->post("entity"))."' and e2c_ent_id = '".$this->db->escape_str($this->input->post("id"))."'");
				
				$strUserList .= "<br/><br/><h3>".$this->lang->line("LAST_UPDATE_AT")."</h3>";
				$maxLastupd = "";
				foreach($getEnt2cat as $catId => $catData) {
					if(isset($catData["e2cLastupd"]) and $catData["e2cLastupd"] > $maxLastupd) {
						$maxLastupd = $catData["e2cLastupd"];
					}
				}
				$strUserList .= (($maxLastupd)?(Common::dateFromDatabase($maxLastupd)):("-"));
			}
			
			echo	"
						new Ext.Window({
							iconCls: 'application_form_add',
							modal: true,
							id: 'windowDataEdit',
							width:800,
							floating: true,
							autoScroll: true,
							minWidth: 800,
							height:500,
							minHeight: 500,
							closeAction:'close',
							maximizable:true,
							title: '".(($this->input->post("id") < 0)?($this->db->escape_str($this->lang->line("ADD_NEW"))):($this->db->escape_str($this->lang->line("EDIT")." - ".$windowTitle)))."',
							bodyStyle: 'background-color:white;',
							layout:'',
							listeners: {
								close: function() {

								}
							},
							
							items: 
								new Ext.TabPanel({
									id: 'dataEditTabs',
									border: false,
									enableTabScroll: true
								})

						}).show();
						
						Ext.getCmp('dataEditTabs').add({
							title: '".(($this->input->post("id") < 0)?($this->db->escape_str($this->lang->line("ADD_NEW"))):($this->db->escape_str($this->lang->line("EDIT")." - ".$windowTitle)))."',
							id: 'Tab_editing_data',
							listeners: {
								activate: function(panel) {
									//Ext.getCmp('dataEditTabs').getActiveTab().getUpdater().refresh();
								}
							},
							border: false,
							layout: 'anchor',
							height: 440,
							autoWidth: true,
							autoScroll: true,
							items: new Ext.FormPanel({
								padding: 10,
								id: 'formDataEdit',
								labelAlign: 'right',
								labelWidth: 70,
								autoHeight: true,
								autoWidth: true,
								autoScroll: true,
								border: false,
								layout: 'anchor',
								defaultType: 'textfield',
								waitMsgTarget: true,
								items: [{
									xtype: 'hidden',
									hidden: true,
									inputType: 'hidden',
									name: 'ENTITY',
									value: '".$this->input->post("entity")."'
									},{
									xtype: 'hidden',
									hidden: true,
									inputType: 'hidden',
									name: 'ID',
									value: '".$this->input->post("id")."'
									},
									".$formElements."
									formCategories
								]
							}),

							tbar: {
								items: [{
									text: '".$this->db->escape_str($this->lang->line("SAVE"))."',
									handler: function() {
										".((isset($ckEditorSave))?($ckEditorSave):(""))."
										if(!Ext.getCmp('formDataEdit').getForm().isValid()) {
											Ext.Msg.show({
												title:'".$this->db->escape_str($this->lang->line("ERROR"))."',
												msg: '".$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))."',
												buttons: Ext.Msg.OK,
												icon: Ext.MessageBox.WARNING
											});
										} else {
											if(Ext.getCmp('formDataEdit').getForm().isDirty() || true) {
												Ext.getCmp('formDataEdit').getForm().submit({
													url: '".site_url()."admin/data_edit_insert_update',
													success: function(form, resp){
														if(resp.result.error) {
															Ext.Msg.show({
																title:'".$this->db->escape_str($this->lang->line("ERROR"))."',
																msg: resp.result.error,
																buttons: Ext.Msg.OK,
																icon: Ext.MessageBox.ERROR
															});
														} else if(resp.result.message) {
															Ext.Msg.show({
																title:'".$this->db->escape_str($this->lang->line("MESSAGE"))."',
																msg: resp.result.message,
																buttons: Ext.Msg.OK,
																icon: Ext.MessageBox.INFO
															});
														} else {
															Ext.getCmp('windowDataEdit').close();
															if(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid')) Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').getStore().reload(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').lastOptions);
															".((strtolower($this->input->post("entity")) != "user")?("if(Ext.getCmp('userGrid')) Ext.getCmp('userGrid').getStore().reload(Ext.getCmp('userGrid').lastOptions);"):(""))."
														}
													}
												});
											} else {
												Ext.getCmp('windowDataEdit').close();
												if(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid')) Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').getStore().reload(Ext.getCmp('".strtolower($this->input->post("entity"))."Grid').lastOptions);
												".((strtolower($this->input->post("entity")) != "user")?("if(Ext.getCmp('userGrid')) Ext.getCmp('userGrid').getStore().reload(Ext.getCmp('userGrid').lastOptions);"):(""))."
											}
										}
									},
									icon: '".MEDIA."icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '".$this->db->escape_str($this->lang->line("CANCEL"))."',
									handler: function() {
										Ext.getCmp('windowDataEdit').close();
									},
									icon: '".MEDIA."icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '".$this->db->escape_str($this->lang->line("RESET"))."',
									handler: function() {
										Ext.getCmp('formDataEdit').getForm().reset();
									}
								}],
								buttonAlign : 'right'
							},
							
							".
							((isset($ckEditor) and $ckEditor)?("
								listeners: {
									afterrender: function() {
										".$ckEditor."
									}
								}
							"):(""))
							."
						}).show();
						
						".((isset($strUserList) and $strUserList)?("
						Ext.getCmp('dataEditTabs').add({
							title: '".$this->db->escape_str($this->lang->line("ADMINISTRATORS"))."',
							id: 'Tab_administrators',
							listeners: {
								activate: function(panel) {
									//Ext.getCmp('dataEditTabs').getActiveTab().getUpdater().refresh();
								}
							},
							border: false,
							layout: 'anchor',
							height: 440,
							autoWidth: true,
							autoScroll: true,
							items: [{
								xtype: 'panel',
								border: false,
								padding: 10,
								html: '".$strUserList."'
							}]
						});
						"):(""))."
						
						";

		}

	}

	function getGroup($SUPERADMIN = FALSE) {
		$this->load->model("group");
		$getGroup = $this->group->getGroup(($SUPERADMIN)?(" grp_id = 1 "):(" grp_id <> 1 "));
		echo Common::arr2jsobj($getGroup, FALSE);
	}

	function getContinent() {
		$this->load->model("continent");
		$getContinent = $this->continent->getContinent();
		echo Common::arr2jsobj($getContinent, FALSE);
	}

	function getCountry() {
		define("OVERRIDE", TRUE);
		$this->load->model("country");
		$getCountry = $this->country->getCountry();
		echo Common::arr2jsobj($getCountry, FALSE);
	}

	function getCity() {
		define("OVERRIDE", TRUE);
		$this->load->model("city");
		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("cityName"));
		}
		$getCity = $this->city->getCity(NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		echo Common::arr2jsobj($getCity, FALSE);
	}

	function getInstitute($override = FALSE) {
		if(is_bool($override) and $override) {
			define("OVERRIDE", TRUE);
		} elseif($override) {
			define("ENTITY", $override);
		}
		$this->load->model("institute");
		$getInstitute = $this->institute->getInstitute();
		echo Common::arr2jsobj($getInstitute, FALSE);
	}

	function basic_data($page = NULL) {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		switch($page) {
			case "SUBJECT": {
				$subpage = array();
				$this->load->model("subject");
				$subpage["getSubject"] = $this->subject->getSubject();
				$this->load->view("admin/basic_data_subject", $subpage);
			} break;
			case "SPONSOR": {
				$subpage = array();
				$this->load->view("admin/basic_data_sponsor", $subpage);
			} break;
			case "MAIN_SLIDER": {
				$subpage = array();
				$this->load->view("admin/basic_data_main_slider", $subpage);
			} break;
			default: {
				$this->load->view("admin/basic_data");
			} break;
		}
	}

	function getSubject($full = FALSE) {
		$this->load->model("subject");
		$where = NULL;
		if(!$full) $where = "a.sub_sub_id is null";
		$getSubject = $this->subject->getSubject($where);
		if($full) {
			$tmp = $getSubject;
			$getSubject = array();
			$ii = 0;
			foreach($tmp as $d) {
				if(isset($d["children"])) {
					foreach($d["children"] as $v) {
						$getSubject[$ii]["subId"] = $v["subId"];
						$getSubject[$ii]["subSubId"] = $v["subSubId"];
						$getSubject[$ii]["subSubName"] = $v["subSubName"];
						$getSubject[$ii]["subName"] = $v["subName"];
						$ii++;
					}
				}
			}
		}
		echo Common::arr2jsobj($getSubject, FALSE);
	}

	function basic_data_insert_update() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$response = array("error" => "");
		$this->load->model("subject");
		if($this->input->get_post("del")) {
			$this->subject->delete($this->input->get_post("subId"));
		} else {
			$insUpd = array(
				"sub_name" => $this->input->get_post("sub_name"),
				"sub_sub_id" => (($this->input->get_post("sub_sub_id"))?($this->input->get_post("sub_sub_id")):(NULL)),
				"sub_url_name" => NULL,
			);

			if(!is_null($insUpd["sub_sub_id"])) {
				$tmp_url_name = $url_name = url_title($this->input->get_post("sub_name"), "underscore", TRUE);
				$free = FALSE;
				$counter = 1;
				while(!$free) {
					$free = TRUE;
					$getSubject = $this->subject->getSubject($where = "a.sub_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("sub_id"))?(" and a.sub_id <> '".$this->db->escape_str($this->input->get_post("sub_id"))."' "):("")));
					if($getSubject) {
						$free = FALSE;
						$url_name = $tmp_url_name.$counter;
						$counter++;
					}
				}
				$insUpd["sub_url_name"] = $url_name;
			}

			if($this->input->get_post("sub_id")) {
				$this->subject->update($this->input->get_post("sub_id"), $insUpd);
			} else {
				$this->subject->insert($insUpd);
			}
		}

		echo	json_encode(array("success" => true) + $response);
	}

	function language() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		//Common::pr($this->lang->language);
		//Common::pr(file(APPPATH."language/hu/study_lang.php"));
		$this->load->view("admin/language");
		/*$handle = fopen(APPPATH."language/hu/study_lang.php", "r");
		echo filesize(APPPATH."language/hu/study_lang.php");
		$read = fread($handle, filesize(APPPATH."language/hu/study_lang.php"));
		Common::pr($read);
		fclose($handle);*/
		//$read = file_get_contents(APPPATH."language/hu/study_lang.php");
		//var_dump($read);
		//echo $read;
	}

	function language_insert_update() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$response = array("error" => "");
		$fp = fopen(APPPATH."language/hu/study_lang.php", "w");
		fwrite($fp, "<?\n\n");
		$language = $this->lang->language;
		asort($language);
		foreach($language as $key => $val) {
			if($key == $this->input->post("lan_id")) {
				fwrite($fp, "\$lang[\"".$key."\"] = \"".str_replace(array("\""), array("\\\""), $this->input->post("lan_text"))."\";\n");
			} else {
				fwrite($fp, "\$lang[\"".$key."\"] = \"".str_replace(array("\""), array("\\\""), $val)."\";\n");
			}
		}
		fclose($fp);
		echo	json_encode(array("success" => true) + $response);
	}

	function article() {
		if(!Common::isAdminJog("PAGE_CAT_ART")) redirect("admin/index");
		$this->load->view("admin/article");
	}

	function get_article($artPosition = NULL) {
		$this->load->model("article_model");
		$where = NULL;
		if(!is_null($artPosition)) {
			if($artPosition == "I") {
				$where = "art_highlight = '".$this->db->escape_str($artPosition)."'";
			} else {
				$where = "art_position = '".$this->db->escape_str($artPosition)."'";
			}
		}
		$getArticle = $this->article_model->getArticle($where, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		$return = array(
			"total" => $this->article_model->getArticleCount($where, $this->input->get_post("fields"), $this->input->get_post("query")),
			"results" => $getArticle
		);
		echo json_encode($return);
	}

	function article_insert_update() {
		if(!Common::isAdminJog("PAGE_CAT_ART")) redirect("admin/index");
		$response = array("error" => "");
		$this->load->model("article_model");
		
		if($this->input->get_post("publish") !== FALSE) {

			$this->load->model("ent2art");
			$getArticleById = $this->article_model->getArticleById($this->input->get_post("ID"));
			$getEnt2artByArtId = $this->ent2art->getEnt2artByArtId($this->input->get_post("ID"));
			
			switch($this->input->get_post("publish")) {
				// töröl unpublished
				case "0": {
					// ekkor töröljük
					if(!$getArticleById->art_name) {
						$this->article_model->delete($this->input->get_post("ID"));
						foreach($getEnt2artByArtId as $ent2art) {
							$this->ent2art->delete($ent2art->e2a_id);
						}
					} else {
						$insUpd = array(
							"art_name_temp" => NULL,
							"art_url_name_temp" => NULL,
							"art_lead_temp" => NULL,
							"art_text_temp" => NULL,
							"art_highlight_temp" => NULL,
							"art_position_temp" => NULL,
							"art_temp_flag" => "N",
						);
						$this->article_model->update($this->input->get_post("ID"), $insUpd);
						foreach($getEnt2artByArtId as $ent2art) {
							if($ent2art->e2a_temp_flag == "I") {
								$this->ent2art->delete($ent2art->e2a_id);
							}
						}
					}
				} break;
				// publish
				case "1": {
					$insUpd = array(
						"art_name_temp" => NULL,
						"art_url_name_temp" => NULL,
						"art_lead_temp" => NULL,
						"art_text_temp" => NULL,
						"art_highlight_temp" => NULL,
						"art_position_temp" => NULL,
						"art_temp_flag" => "N",
						"art_name" => $getArticleById->art_name_temp,
						"art_url_name" => $getArticleById->art_url_name_temp,
						"art_lead" => $getArticleById->art_lead_temp,
						"art_text" => $getArticleById->art_text_temp,
						"art_highlight" => $getArticleById->art_highlight_temp,
						"art_position" => $getArticleById->art_position_temp,
					);
					$this->article_model->update($this->input->get_post("ID"), $insUpd);
					foreach($getEnt2artByArtId as $ent2art) {
						if($ent2art->e2a_temp_flag == "N") {
							$this->ent2art->delete($ent2art->e2a_id);
						} else {
							$this->ent2art->update($ent2art->e2a_id, array("e2a_temp_flag" => "N"));
						}
					}
				} break;
				// töröl published
				case "2": {
					$insUpd = array(
						"art_name_temp" => Common::coalesce(array($getArticleById->art_name, $getArticleById->art_name_temp)),
						"art_url_name_temp" => Common::coalesce(array($getArticleById->art_url_name, $getArticleById->art_url_name_temp)),
						"art_lead_temp" => Common::coalesce(array($getArticleById->art_lead, $getArticleById->art_lead_temp)),
						"art_text_temp" => Common::coalesce(array($getArticleById->art_text, $getArticleById->art_text_temp)),
						"art_highlight_temp" => Common::coalesce(array($getArticleById->art_highlight, $getArticleById->art_highlight_temp)),
						"art_position_temp" => Common::coalesce(array($getArticleById->art_position, $getArticleById->art_position_temp)),
						"art_name" => NULL,
						"art_temp_flag" => "I",
					);
					$this->article_model->update($this->input->get_post("ID"), $insUpd);
					foreach($getEnt2artByArtId as $ent2art) {
						if($ent2art->e2a_temp_flag == "N") {
							$vanTemp = FALSE;
							foreach($getEnt2artByArtId as $ent2art2) {
								if($ent2art->e2a_cou_id == $ent2art2->e2a_cou_id and $ent2art->e2a_city_id == $ent2art2->e2a_city_id and $ent2art->e2a_ins_id == $ent2art2->e2a_ins_id and $ent2art->e2a_maj_id == $ent2art2->e2a_maj_id and $ent2art->e2a_sub_id == $ent2art2->e2a_sub_id and $ent2art2->e2a_temp_flag == "I") {
									$vanTemp = TRUE;
								}
							}
							if(!$vanTemp) {
								$this->ent2art->update($ent2art->e2a_id, array("e2a_temp_flag" => "I"));
							} else {
								$this->ent2art->delete($ent2art->e2a_id);
							}
						}
					}
				} break;
			}
			
			//Common::pr($getArticleById); Common::pr($getEnt2artByArtId);

		} else {
		
			if($this->input->get_post("del")) {
				$this->article_model->delete($this->input->get_post("artId"));
			} elseif($this->input->get_post("sort") and intval($this->input->get_post("position"))) {
				if($this->input->post("artPosition") == "I") {
					$where = "art_highlight = '".$this->db->escape_str($this->input->post("artPosition"))."'";
				} else {
					$where = "art_position = '".$this->db->escape_str($this->input->post("artPosition"))."'";
				}
				$getArticle = $this->article_model->getArticle($where, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
				$found = FALSE;
				$artOrder = 1;
				foreach($getArticle as $art) {
					if($art["artId"] == $this->input->post("artId")) {
						$this->article_model->update($art["artId"], array("art_order" => $this->input->post("position")));
						$found = TRUE;
					} else {
						$this->article_model->update($art["artId"], array("art_order" => $artOrder));
						$artOrder++;
						if($artOrder == $this->input->post("position")) {
							$artOrder++;
						}
					}
				}
			} else {
				$csat = array("sub", "cou", "city", "ins", "maj");
				
				if(Common::isAdmin()) {
					$vanCsatolas = FALSE;
					foreach($csat as $ent) {
						$post_ent = $this->input->get_post($ent."_id");
						if($post_ent and isset($post_ent[0]) and ($post_ent[0])) {
							$vanCsatolas = TRUE;
						}
					}
					if(!$vanCsatolas) {
						$response["error"] .= $this->lang->line("SET_AT_LEAST_ONE_LINK");
					}
				}
				
				if(!$response["error"]) {

					$tmp_url_name = $url_name = url_title($this->input->get_post("art_name"), "underscore", TRUE);
					$free = FALSE;
					$counter = 1;
					while(!$free) {
						$free = TRUE;
						$getArticle = $this->article_model->getArticle($where = "art_url_name = '".$this->db->escape_str($url_name)."'".(($this->input->get_post("art_id"))?(" and art_id <> '".$this->db->escape_str($this->input->get_post("art_id"))."' "):("")));
						if($getArticle) {
							$free = FALSE;
							$url_name = $tmp_url_name.$counter;
							$counter++;
						}
					}

					$szotar = Common::szotar("ARTPOS");
					// kiemelt cikk csak centerben lehet
					if(in_array($this->input->get_post("art_position"), array("F", "H", "R"))) {
						$_POST["art_highlight"] = "N";
					}
					$insUpd = array(
						"art_name_temp" => $this->input->get_post("art_name"),
						"art_url_name_temp" => $url_name,
						"art_lead_temp" => $this->input->get_post("art_lead"),
						"art_text_temp" => $this->input->get_post("art_text"),
						"art_position_temp" => ((in_array($this->input->get_post("art_position"), array_keys($szotar["ARTPOS"])))?($this->input->get_post("art_position")):("C")),
						"art_highlight_temp" => $this->input->get_post("art_highlight")?$this->input->get_post("art_highlight"):"N",
						"art_temp_flag" => "I",
						"art_usr_id" => $this->session->userdata("usrId"),
					);
					if($this->input->get_post("art_id")) {
						$this->article_model->update($this->input->get_post("art_id"), $insUpd);
						$artId = $this->input->get_post("art_id");
					} else {
						$insUpd["art_createtime"] = Common::now();
						$insUpd["art_url_name"] = $url_name;
						//$insUpd["art_name"] = $this->input->get_post("art_name");
						$artId = $this->article_model->insert($insUpd);
					}
					/* Csatolasok mentese */
					$this->load->model("ent2art");
					$getEnt2art = $this->ent2art->getEnt2art($where = "e2a_art_id = '".intval($artId)."' and e2a_temp_flag = 'I'");
					foreach($csat as $ent) {
						if($this->input->get_post($ent."_id") and count($this->input->get_post($ent."_id"))) {
							foreach($this->input->get_post($ent."_id") as $ID) {
								if($ID and (!isset($getEnt2art[$artId][$ent]) or !in_array($ID, $getEnt2art[$artId][$ent]))) {
									$this->ent2art->insert(array("e2a_art_id" => $artId, "e2a_temp_flag" => "I", "e2a_".$ent."_id" => $ID));
								}
							}
						}
						if(isset($getEnt2art[$artId][$ent])) {
							foreach($getEnt2art[$artId][$ent] as $e2aId => $ID) {
								if(!in_array($ID, $this->input->get_post($ent."_id"))) {
									$this->ent2art->delete($e2aId);
								}
							}
						}
					}
					
				}
			}
		
		}
		echo	json_encode(array("success" => true) + $response);
		if(Common::isSuperAdmin()) {
			$this->article_model->fixOrder();
		}
	}

	function get_continent($obj = FALSE) {
		$this->load->model("continent");

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("couName"));
		}

		$getContinent = $this->continent->getContinent($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		if($obj) {
			echo Common::arr2jsobj($getContinent, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->continent->getContinentCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getContinent
			);
			echo json_encode($return);
		}
	}

	function get_country($obj = FALSE) {
		$this->load->model("country");
		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("couName"));
		}

		$getCountry = $this->country->getCountry($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		if($obj) {
			echo Common::arr2jsobj($getCountry, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->country->getCountryCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getCountry
			);
			echo json_encode($return);
		}
	}

	function get_city($couId = FALSE, $obj = FALSE) {
		$this->load->model("city");

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("cityName"));
		}

		if($this->input->get_post("couId")) {
			$couId = $this->input->get_post("couId");
		}
		$getCity = $this->city->getCity($where = (($couId)?("city_cou_id = '".intval($couId)."'"):(NULL)), $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		
		// dropdown esetben kipucoljuk
		if(!$this->input->get_post("sort")) {
			foreach($getCity as $ii => $city) {
				$getCity[$ii] = array(
					"cityId" => $city["cityId"],
					"cityName" => $city["cityName"],
					"couName" => $city["couName"],
				);
			}
		}
		
		if($obj) {
			echo Common::arr2jsobj($getCity, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->city->getCityCount($where = (($couId)?("city_cou_id = '".intval($couId)."'"):(NULL)), $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getCity
			);
			echo json_encode($return);
		}
	}

	function get_institute($obj = FALSE, $type = NULL, $ENTITY = NULL) {

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("insName"));
		}
		
		$where = NULL;
		$this->load->model("institute");
		if(!is_null($type)) {
			switch($type) {
				case "IIN": { $where = "ins_ins_id is null"; } break;
				case "FAC": { $where = "ins_ins_id is not null"; } break;
			}
		}
		if(!is_null($ENTITY)) {
			define("ENTITY", $ENTITY);
		}
		$getInstitute = $this->institute->getInstitute($where, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));

		if($obj) {
			echo Common::arr2jsobj($getInstitute, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->institute->getInstituteCount($where, $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getInstitute
			);
			echo json_encode($return);
		}
	}

	function get_accomodation($obj = FALSE) {

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("accName"));
		}
		
		$where = NULL;
		if($this->input->get("insId")) $where = "a2im_ins_id = '".intval($this->input->get("insId"))."'";
		$this->load->model("accomodation");

		$getAccomodation = $this->accomodation->getAccomodation($where, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));

		if($obj) {
			echo Common::arr2jsobj($getAccomodation, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->accomodation->getAccomodationCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getAccomodation
			);
			echo json_encode($return);
		}
	}
	
	function get_subject($obj = FALSE) {
		$this->load->model("subject");

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("subName"));
		}

		$getSubject = $this->subject->getSubject($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		if($obj) {
			echo Common::arr2jsobj($getSubject, $keytoobj = FALSE);
		}
	}	
	
	function get_major($insId = FALSE, $obj = FALSE) {
		$this->load->model("major");

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("majName"));
		}

		$getMajor = $this->major->getMajor($where = ((is_numeric($insId) and $insId > 0)?("maj_ins_id = '".intval($insId)."'"):(NULL)), $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		if($obj) {
			echo Common::arr2jsobj($getMajor, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->major->getMajorCount($where = ((is_numeric($insId))?("maj_ins_id = '".intval($insId)."'"):(NULL)), $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getMajor
			);
			echo json_encode($return);
		}
	}

	function get_scholarship($insId = FALSE, $obj = FALSE) {
		$this->load->model("scholarship");

		if($this->input->get_post("query") and !$this->input->get_post("valuesqry") and !$this->input->get_post("fields")) {
			$_POST["fields"] = json_encode(array("majName"));
		}

		$getScholarship = $this->scholarship->getScholarship($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		if($obj) {
			echo Common::arr2jsobj($getScholarship, $keytoobj = FALSE);
		} else {
			$return = array(
				"total" => $this->scholarship->getScholarshipCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
				"results" => $getScholarship
			);
			echo json_encode($return);
		}
	}
	
	function newsletter() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->view("admin/newsletter");
	}

	function get_newsletter() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->model("newsletter");
		$getNewsletter = $this->newsletter->getNewsletter($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		$return = array(
			"total" => $this->newsletter->getNewsletterCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
			"results" => $getNewsletter
		);
		echo json_encode($return);
	}

	function newsletter_import() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->model("user");
		echo $this->user->getSubscribers();
	}

	function newsletter_insert_update() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$response = array("error" => "");
		$this->load->model("newsletter");
		if($this->input->get_post("del")) {
			$this->newsletter->delete($this->input->get_post("nltId"));
		} else {
			$insUpd = array(
				"nlt_subject" => $this->input->get_post("nlt_subject"),
				"nlt_text" => $this->input->get_post("nlt_text"),
			);
			if($this->input->get_post("nlt_id")) {
				$this->newsletter->update($this->input->get_post("nlt_id"), $insUpd);
			} else {
				$this->newsletter->insert($insUpd);
			}
		}
		echo	json_encode(array("success" => true) + $response);
	}

	function email_send() {
		$response = array("error" => "");

		if(!$this->input->get_post("subject")) {
			$response["error"] .= $this->lang->line("EMAIL_SUBJECT_IS_REQUIRED");
		}

		if(!$this->input->get_post("text")) {
			$response["error"] .= $this->lang->line("TEXT_OF_THE_MESSAGE_IS_REQUIRED");
		}

		if(!$response["error"] and preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $this->input->get_post("email"))) {
			$response["message"] = Common::sendEmail($this->input->get_post("email"), $this->input->get_post("subject"), $this->input->get_post("text"));
		}
		echo	json_encode(array("success" => true) + $response);
	}

	function newsletter_send() {
		$response = array();
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->model("newsletter");
		$getNewsletter = $this->newsletter->getNewsletter("nlt_id = '".$this->db->escape_str($this->input->get_post("nlt_id"))."'");
		if($getNewsletter) {
			$nlt = current($getNewsletter);
			$arrList = explode(",", $this->input->post("nlt_address_list"));
			foreach($arrList as $email) {
				$email = trim($email);
				if(preg_match("/^[^0-9][A-z0-9_-]+([.][A-z0-9_-]+)*[@][A-z0-9_-]+([.][A-z0-9_-]+)*[.][A-z]{2,4}$/i", $email)) {
					$response["message"] = Common::sendEmail($email, $nlt["nltSubject"], $nlt["nltText"]);
				}
			}
			$this->newsletter->update($nlt["nltId"], array("nlt_sent" => "I"));
		}
		echo	json_encode(array("success" => true) + $response);
	}

	function logs() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->view("admin/logs");
	}

	function get_logs() {
		if(!Common::isSuperAdmin()) redirect("admin/index");
		$this->load->model("sys_log");
		$getSys_log = $this->sys_log->getSys_log($where = NULL, $this->input->get_post("start"), $this->input->get_post("limit"), $this->input->get_post("fields"), $this->input->get_post("query"), $this->input->get_post("sort"), $this->input->get_post("dir"));
		$return = array(
			"total" => $this->sys_log->getSys_logCount($where = NULL, $this->input->get_post("fields"), $this->input->get_post("query")),
			"results" => $getSys_log
		);
		echo json_encode($return);
	}


	function file_upload() {
		if(!$this->input->post("ENTITY") or !in_array($this->input->post("ENTITY"), array("COU", "CITY", "INS", "FAC", "MAJ", "ACC", "SCH", "MAIN_SLIDER")) or !is_numeric($this->input->post("ID"))) {
			return FALSE;
		}

		$response["error"] = "";
		$save_path = $_SERVER["DOCUMENT_ROOT"].str_replace("media", "uploads", MEDIA);
		$valid_chars_regex = '.A-Z0-9_ !@#$%^&()+={}\[\]\',~`-';
		$MAX_FILENAME_LENGTH = 260;

		$max_file_size_in_bytes = 2147483647; // 2GB in bytes
		$upload_name = 'Filedata';

		$POST_MAX_SIZE = ini_get('post_max_size');
		$unit = strtoupper(substr($POST_MAX_SIZE, -1));
		$multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));

		if((int)$_SERVER['CONTENT_LENGTH'] > $multiplier*(int)$POST_MAX_SIZE && $POST_MAX_SIZE) {
			$response["error"] .= $this->lang->line("POST_EXCEEDED_MAXIMUM_ALLOWED_SIZE");
			die('{success:false,error:'.json_encode($this->lang->line("POST_EXCEEDED_MAXIMUM_ALLOWED_SIZE")).'}');
		}

		// Other variables
		$file_name = '';
		$uploadErrors = array(
			0 => $this->lang->line("THERE_IS_NO_ERROR_THE_FILE_UPLOADED_WITH_SUCCESS"),
			1 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_UPLOAD_MAX_FILESIZE_DIRECTIVE"),
			2 => $this->lang->line("THE_UPLOADED_FILE_EXCEEDS_THE_MAX_FILE_SIZE_DIRECTIVE_THAT_WAS_SPECIFIED_IN_THE_HTML_FORM"),
			3 => $this->lang->line("THE_UPLOADED_FILE_WAS_ONLY_PARTIALLY_UPLOADED"),
			4 => $this->lang->line("NO_FILE_WAS_UPLOADED"),
			6 => $this->lang->line("MISSING_A_TEMPORARY_FOLDER")
		);

		// Validate the upload
		if (!isset($_FILES[$upload_name])) {
			$response["error"] .= $this->lang->line("NO_UPLOAD_FOUND");
			die('{success:false,error:'.json_encode($this->lang->line("NO_UPLOAD_FOUND")).'}');
		} else if (isset($_FILES[$upload_name]["error"]) && $_FILES[$upload_name]["error"] != 0) {
			$response["error"] .= $uploadErrors[$_FILES[$upload_name]["error"]];
			die('{success:false,error:'.json_encode($uploadErrors[$_FILES[$upload_name]["error"]]).'}');
		} else if (!isset($_FILES[$upload_name]["tmp_name"]) || !@is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
			$response["error"] .= $this->lang->line("UPLOAD_FAILED_IS_UPLOADED_FILE_TEST");
			die('{success:false,error:'.json_encode($this->lang->line("UPLOAD_FAILED_IS_UPLOADED_FILE_TEST")).'}');
		} else if (!isset($_FILES[$upload_name]['name'])) {
			$response["error"] .= $this->lang->line("FILE_HAS_NO_NAME");
			die('{success:false,error:'.json_encode($this->lang->line("FILE_HAS_NO_NAME")).'}');
		}

		// Validate the file size (Warning: the largest files supported by this code is 2GB)
		$file_size = @filesize($_FILES[$upload_name]["tmp_name"]);
		if (!$file_size || $file_size > $max_file_size_in_bytes) {
			$response["error"] .= $this->lang->line("FILE_EXCEEDS_THE_MAXIMUM_ALLOWED_SIZE");
			die('{success:false,error:'.json_encode($this->lang->line("FILE_EXCEEDS_THE_MAXIMUM_ALLOWED_SIZE")).'}');
		}

		if ($file_size <= 0) {
			$response["error"] .= $this->lang->line("FILE_SIZE_OUTSIDE_ALLOWED_LOWER_BOUND");
			die('{success:false,error:'.json_encode($this->lang->line("FILE_SIZE_OUTSIDE_ALLOWED_LOWER_BOUND")).'}');
		}

		$rand = mt_rand()."_".uniqid("", TRUE);

		$path_info = pathinfo($_FILES[$upload_name]["name"]);
		$file_extension = $path_info["extension"];

		$file_name = $this->input->post("ENTITY")."_".$this->input->post("ID")."_".$rand.".".$file_extension;
		//Common::pr(getimagesize($_FILES[$upload_name]["tmp_name"]));

		list($width, $height, $type, $attr)= getimagesize($_FILES[$upload_name]["tmp_name"]);
		if(!$width) {
			die('{success:false,error:'.json_encode($this->lang->line("INVALID_FILE_FORMAT")).'}');
		}

		if(!$height or $height < 110) {
			die('{success:false,error:'.json_encode($this->lang->line("INVALID_FILE_FORMAT")).'}');
		}

		if (!@move_uploaded_file($_FILES[$upload_name]["tmp_name"], $save_path.$file_name)) {
			$response["error"] .= $this->lang->line("FILE_COULD_NOT_BE_SAVED");
			die('{success:false,error:'.json_encode($this->lang->line("FILE_COULD_NOT_BE_SAVED")." - ".$save_path.$file_name).'}');
		} else {
			$file_hash = md5(file_get_contents($save_path.$file_name));
			
			// thumb
			$config['image_library'] = 'gd2';
			$config['source_image'] = $save_path.$file_name;
			$config['create_thumb'] = TRUE;
			$config['maintain_ratio'] = TRUE;
			$config['master_dim'] = 'height';
			$config['width'] = 180;
			$config['height'] = 110;
			$this->load->library('image_lib', $config);
			$this->image_lib->resize();

			$thumb = preg_split("/\./", $file_name);
			$len = strlen($thumb[count($thumb)-1]);
			list($thumbwidth, $thumbheight, $type, $attr) = getimagesize(base_url().UPLOADS.substr($file_name, 0, -($len+1))."_thumb.".$thumb[count($thumb)-1]);

			$this->image_lib->clear();
			$config = array();

			// resize
			$config['image_library'] = 'gd2';
			$config['source_image'] = $save_path.$file_name;
			$config['maintain_ratio'] = TRUE;
			if($width > 900 or $height > 500) {
				$config['width'] = 900;
				$config['height'] = 500;
			} else {
				$config['width'] = $width;
				$config['height'] = $height;
			}
			$config['thumb_marker'] = "_resized";
			$this->image_lib->initialize($config);
			$this->image_lib->resize();
			list($resizedwidth, $resizedheight, $type, $attr) = getimagesize(base_url().UPLOADS.substr($file_name, 0, -($len+1))."_resized.".$thumb[count($thumb)-1]);

			$this->load->model("ent2image");
			$e2iId = $this->ent2image->insert(array(
				"e2i_".strtolower($this->input->post("ENTITY"))."_id" => $this->input->post("ID"),
				"e2i_hash" => $file_hash,
				"e2i_image_name_original" => basename($_FILES[$upload_name]['name']),
				"e2i_image_name" => $file_name,
				"e2i_width" => $width,
				"e2i_height" => $height,
				"e2i_thumb_width" => $thumbwidth,
				"e2i_thumb_height" => $thumbheight,
				"e2i_resized_width" => $resizedwidth,
				"e2i_resized_height" => $resizedheight,
			));

		}

		if($response["error"]) {
			echo	"{success:false,error:".json_encode($response["error"])."}";
		} else {
			echo	"{'success':true}";
		}

	}

	function get_ent2image($ENTITY = "", $ID = "") {
		$getEnt2image = array();
		$this->load->model("ent2image");
		if(in_array($ENTITY, array("COU", "CITY", "INS", "MAJ", "ACC", "SCH"))) {
			$getEnt2image = $this->ent2image->getEnt2image($where = "e2i_".strtolower($ENTITY)."_id = '".$this->db->escape_str($ID)."'");
		} elseif($ENTITY == "MAIN_SLIDER") {
			$getEnt2image = $this->ent2image->getEnt2image($where = "e2i_cou_id is null and e2i_city_id is null and e2i_ins_id is null and e2i_maj_id is null");
		}
		echo json_encode(array("images" => $getEnt2image));
	}
	
	function get_ins_ent2image($ENTITY = "", $ID = "") {
		$insId = 0;
		switch($ENTITY) {
			case "MAJ": {
				$this->load->model("major");
				$getMajor = $this->major->getMajor("maj_id = '".intval($ID)."'");
				$insId = $getMajor[0]["majInsId"];
			} break;
			case "INS": {
				$insId = $ID;
			} break;
		}
		$getEnt2imagebyinsId = array();
		if($insId) {
			$this->load->model("ent2image");
			$getEnt2imagebyinsId = $this->ent2image->getEnt2imagebyinsId($insId);
		}
		echo json_encode(array("images" => $getEnt2imagebyinsId));
	}

	function ent2image_insert_update() {
		$this->load->model("ent2image");
		if($this->input->get_post("del")) {
			$ids = preg_split("/\|/", $this->input->post("e2iId"));
			foreach($ids as $e2iId) {
				$this->ent2image->delete($e2iId);
			}
		} elseif($this->input->get_post("copy") and $this->input->get_post("e2iId")) {
			if(!is_array($this->input->get_post("e2iId"))) {
				$_POST["e2iId"] = array($this->input->get_post("e2iId"));
			}
			$getEnt2image_copy = $this->ent2image->getEnt2image("e2i_id in (".implode(",", $this->input->get_post("e2iId")).")");
			if(count($getEnt2image_copy)) {
				$getEnt2image = $this->ent2image->getEnt2image("e2i_".strtolower($this->input->get_post("ENTITY"))."_id = ".intval($this->input->get_post("ID")));
				foreach($getEnt2image_copy as $e2i_copy) {
					$isset = FALSE;
					foreach($getEnt2image as $e2i) {
						if($e2i_copy["e2iHash"] == $e2i["e2iHash"]) {
							$isset = TRUE;
						}
					}
					if(!$isset) {
						$this->ent2image->insert(array(
							"e2i_".strtolower($this->input->get_post("ENTITY"))."_id" => $this->input->get_post("ID"),
							"e2i_image_name" => $e2i_copy["e2iImageName"],
							"e2i_image_name_original" => $e2i_copy["e2iImageNameOriginal"],
							"e2i_width" => $e2i_copy["e2iWidth"],
							"e2i_height" => $e2i_copy["e2iHeight"],
							"e2i_thumb_width" => $e2i_copy["e2iThumbWidth"],
							"e2i_thumb_height" => $e2i_copy["e2iThumbHeight"],
							"e2i_resized_width" => $e2i_copy["e2iResizedWidth"],
							"e2i_resized_height" => $e2i_copy["e2iResizedHeight"],
							"e2i_hash" => $e2i_copy["e2iHash"],
						));
					}
				}
			}
		} else {
			$this->ent2image->update($this->input->post("e2iId"), array("e2i_alt" => $this->input->post("e2i_alt")));
		}
	}

	function country_insert_update() {
		$this->load->model("country");
		$this->country->update($this->input->post("couId"), array("cou_priority" => ((is_numeric($this->input->post("val")) and $this->input->post("val") >= 0 and $this->input->post("val") <= 100 )?($this->input->post("val")):(0))));
	}


	function city_insert_update() {
		$this->load->model("city");
		$this->city->update($this->input->post("cityId"), array("city_priority" => ((is_numeric($this->input->post("val")) and $this->input->post("val") >= 0 and $this->input->post("val") <= 100 )?($this->input->post("val")):(0))));
	}

	function institute_insert_update() {
		$this->load->model("institute");
		$this->institute->update($this->input->post("insId"), array("ins_priority" => ((is_numeric($this->input->post("val")) and $this->input->post("val") >= 0 and $this->input->post("val") <= 100 )?($this->input->post("val")):(0))));
	}

	function getSzotar($type = NULL, $progType = NULL) {
		if($this->input->post("progType")) $progType = $this->input->post("progType");
		switch($type) {
			case "PROGTYPE_2": {
				$szotar = Common::szotar(array("PROGTYPE_2"));
				//Common::pr($szotar); exit;
				if($progType == "LS") {
					unset($szotar["PROGTYPE_2"]["FD"]);
					unset($szotar["PROGTYPE_2"]["AYS"]);
				}
				echo Common::arr2jsobj($szotar["PROGTYPE_2"], TRUE);
			} break;
		}
	}

	function password_change($panel = NULL) {
		$this->load->view("admin/password_change");
	}

	function password_change_insert_update() {
		$response = array("error" => "");

		$this->load->model("user");

		if(!$this->input->get_post("usr_password")) {
			$response["error"] .= $this->lang->line("PASSWORD_IS_REQUIRED");
		}

		if($this->input->get_post("usr_password") and $this->input->get_post("usr_password") <> $this->input->get_post("usr_password_re")) {
			$response["error"] .= $this->lang->line("THE_ENTERED_PASSWORDS_ARE_NOT_THE_SAME");
		}

		if(!$response["error"]) {
			if($this->input->get_post("usr_password")) {
				$insUpd["usr_password"] = md5($this->input->get_post("usr_password"));
			}
			$this->user->update($this->session->userdata("usrId"), $insUpd);
		}

		echo	json_encode(array("success" => true) + $response);

	}

	// nem megerositett admin atkerulese admin csoportba
	function usr2grp_insert_update() {
	
		$this->load->model("user");
		$getUser = $this->user->getUser($where = "u2g_usr_id is not null");
		if(isset($getUser[$this->input->get_post("usrId")])) {
		
			$this->load->model("usr2grp");
			$getUsr2grp = $this->usr2grp->getUsr2grp($where = "u2g_usr_id = '".$this->input->get_post("usrId")."'");
			foreach($getUsr2grp as $u2g_id) {
				$this->usr2grp->delete($u2g_id);
			}
			$this->usr2grp->insert(array("u2g_usr_id" => $this->input->get_post("usrId"), "u2g_grp_id" => 2));

			$getUser = $this->user->getUser("usr_id = '".intval($this->input->get_post("usrId"))."'");
			Common::sendEmail($getUser[intval($this->input->get_post("usrId"))]["usrEmail"], $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_SUBJECT"), $this->lang->line("ACCOUNT_ACTIVATED_AS_ADMIN_EMAIL_BODY"), $replace = array("<FULL_NAME>" => (($getUser[intval($this->input->get_post("usrId"))]["fullName"])?($getUser[intval($this->input->get_post("usrId"))]["fullName"]):($getUser[intval($this->input->get_post("usrId"))]["usrEmail"]))), $attach = NULL);
			
			if($this->input->get_post("insId")) {
				$this->load->model("usr2ent");
				$this->usr2ent->insert(array("u2e_usr_id" => $this->input->get_post("usrId"), "u2e_ins_id" => $this->input->get_post("insId")));
			}
			
		}
	}

	function image_crop($e2iId = NULL) {
		if(!is_null($e2iId)) {
			$this->load->model("ent2image");
			$getEnt2image = $this->ent2image->getEnt2image($where = "e2i_id = '".$this->db->escape_str($e2iId)."'");
			if(count($getEnt2image)) {
				if($this->input->post("remove")) {
					$this->ent2image->update($getEnt2image[0]["e2iId"], array("e2i_cropped" => "N"));
				} else {
					$img = BASEPATH."..".UPLOADS.$getEnt2image[0]["e2iImageNameResized"];

					$config['image_library'] = 'gd2';
					$config['source_image'] = $img;
					$config['maintain_ratio'] = FALSE;
					$newimg = $config['new_image'] = str_replace("_resized", "_cropped", BASEPATH."..".UPLOADS.$getEnt2image[0]["e2iImageNameResized"]);
					$config['width'] = $this->input->post("width");
					$config['height'] = $this->input->post("height");
					$config['x_axis'] = $this->input->post("x");
					$config['y_axis'] = $this->input->post("y");
					$this->load->library('image_lib', $config);
					if($this->image_lib->crop()) {
						$this->ent2image->update($getEnt2image[0]["e2iId"], array("e2i_cropped" => "I"));
					}

					if($this->input->post("width") != 660 or $this->input->post("height") != 350) {
						$config['image_library'] = 'gd2';
						$config['source_image'] = $newimg;
						$config['maintain_ratio'] = FALSE;
						$config['width'] = 660;
						$config['height'] = 350;
						$config['new_image'] = $newimg;
						$this->image_lib->initialize($config);
						$this->image_lib->resize();
					}

				}

				//Common::pr($config);
				//echo $this->image_lib->display_errors();
			}
		}
	}
	
	function get_page_category($return = FALSE) {
		$szotar = Common::szotar("ENTITY");
		if(isset($szotar["ENTITY"])) {
			$pageCat = array();
			//if(Common::isAdminJog("PAGE_CAT", "IMP")) 
			$pageCat["IMP"] = $szotar["ENTITY"]["IMP"];
			//if(Common::isAdminJog("PAGE_CAT", "MAJ")) 
			$pageCat["MAJ"] = $szotar["ENTITY"]["MAJ"];
			//if(Common::isAdminJog("PAGE_CAT", "SCH")) 
			$pageCat["SCH"] = $szotar["ENTITY"]["SCH"];
			//if(Common::isAdminJog("PAGE_CAT", "WAS")) 
			$pageCat["WAS"] = $szotar["ENTITY"]["WAS"];
			//if(Common::isAdminJog("PAGE_CAT", "INT")) 
			$pageCat["INT"] = $szotar["ENTITY"]["INT"];
			//if(Common::isAdminJog("PAGE_CAT", "ACC")) 
			$pageCat["ACC"] = $szotar["ENTITY"]["ACC"];
			//if(Common::isAdminJog("PAGE_CAT", "ART")) 
			$pageCat["ART"] = $szotar["ENTITY"]["ART"];
			//if(Common::isAdminJog("PAGE_CAT", "FAC")) 
			$pageCat["FAC"] = $szotar["ENTITY"]["FAC"];
			if($return) return $pageCat;

			else echo Common::arr2jsobj($pageCat, $keytoobj = TRUE);
		}
	}

	function messages() {
		$this->load->model("message");
		if(Common::isSuperAdmin()) {
			$subpage["getMessage"] = $this->message->getMessage();
		} else { 
			$this->load->model("usr2ent");
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."'");
			$getUsr2entINS = (($getUsr2ent and isset($getUsr2ent["INS"]))?($getUsr2ent["INS"]["children"]):(array()));
			$subpage["getMessage"] = $this->message->getMessage($where = "(mes_sender_usr_id = '".$this->db->escape_str($this->session->userdata("usrId"))."' ".((count($getUsr2entINS))?(" or mes_ins_id in (".implode(",", $getUsr2entINS).")"):(""))." )");
		}
		$this->load->view("admin/messages", $subpage);
	}
	
	function getCurrency() {
		$this->load->model("currency");
		$getCurrency = $this->currency->getCurrency();
		echo Common::arr2jsobj($getCurrency, FALSE);
	}

	private function _gen_pdf($html, $name, $paper="A4") {
		$this->load->library("mpdf/mpdf");
		$mpdf=new mPDF("utf-8",$paper);
		
		// unwrap remove
		$html = str_replace(array("{unwrap}", "{/unwrap}"), array("", ""), $html);
		
		$mpdf->WriteHTML($html);
		$mpdf->Output(PDFS.$name, "F");
	}

	function getUsr2ent() {
		header("Content-type:text/javascript");
		$this->load->model("user");
		$this->load->model("usr2ent");
		if($this->user->getUser("usr_id = '".intval($this->input->post("usrId"))."'")) {
			$getPageCategory = $this->get_page_category($return = TRUE);
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->input->post("usrId"))."'");
			if(isset($getUsr2ent["INS"]["children"])) {
				$strHelp = "";
				//Common::pr($getUsr2ent);
				$this->load->model("institute");
				define("OVERRIDE", TRUE);
				$getInstitute = $this->institute->getInstitute("ins_id in (".implode(", ", $getUsr2ent["INS"]["children"]).")");
				if(count($getInstitute)) {
					
					?>
					var reader<?=$this->input->post("usrId")?> = new Ext.data.ArrayReader({}, [
						{name: 'insId'},
						{name: 'insName'}
						<?
						$ii = 0;
						foreach($getPageCategory as $szo_rnev => $szo_hnev) {
							echo	",{name: '".$this->db->escape_str($szo_rnev)."'}";
							$strHelp .= (($strHelp and $ii%3 == 0)?("<br/>"):("")) . "<div style=\"width: 33%; display: inline-block;\"><b>". $this->db->escape_str($szo_rnev) . "</b>: " .$this->db->escape_str($szo_hnev) . "</div>";
							$ii++;
						}
						?>
					]);
					
					var store<?=$this->input->post("usrId")?> = new Ext.data.Store({
						reader: reader<?=$this->input->post("usrId")?>,
						data: [
							<?
								$first = TRUE;
								
								foreach($getInstitute as $ins) {
									echo	((!$first)?(","):(""))."
											[
											\"".$ins["insId"]."\",
											\"".$this->db->escape_str($ins["insName"]." (".$ins["cityName"]).")\"
											";
									foreach($getPageCategory as $szo_rnev => $szo_hnev) {
												echo	"," . ((isset($getUsr2ent["PAGE_CAT_".$szo_rnev]["u2eIds"][$ins["insId"]]))?("true"):((isset($this->getUsr2ent["PAGE_CAT_".$szo_rnev]["u2eIds"][$ins["insId"]]) or Common::isSuperAdmin())?("false"):("'disabled'")));
									}
									echo	"]";
									$first = FALSE;
								}

							?>
						],
						sortInfo:{field: 'insId', direction: "ASC"},
						groupField:'insId'
					});
					
					var grid<?=$this->input->post("usrId")?> = new Ext.grid.EditorGridPanel({
						store: store<?=$this->input->post("usrId")?>,
						viewConfig:{
							emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
						},

						columns: [
							{id:'insName', header: '<?=$this->db->escape_str($this->lang->line("INSTITUTE"))?>', width: 200, sortable: true, dataIndex: 'insName'}
							<? foreach($getPageCategory as $szo_rnev => $szo_hnev) { ?>
								<? if(Common::isAdminJog("PAGE_CAT_".$szo_rnev )) { //  and isset($this->getUsr2ent["PAGE_CAT_".$szo_rnev]["u2eIds"][$this->input->post("usrId")])?>
									,{header: '<?=$szo_rnev?>', width: 45, sortable: true, align: 'center', dataIndex: '<?=$szo_rnev?>', renderer: function(val, m, record) { 
										if(val == 'disabled') return '';
										else return (new Ext.ux.grid.CheckColumn()).renderer(val, '', record);
									}, xtype: 'checkcolumn', editor: { xtype: 'checkbox', cls: 'x-grid-checkheader-editor' }, listeners : { checkchange : function(column, recordIndex, checked, record) { 
											Ext.Ajax.request({url: '<?=site_url()?>admin/usr2ent_insert_update', params: 'usrId=<?=$this->input->post("usrId")?>&ENTITY=<?=$szo_rnev?>&insId=' + record.data.insId + '&checked=' + ((checked)?(1):(0)),
												success: function(result, request){
													var json = Ext.decode(result.responseText);
													if(json.error) {
														Ext.Msg.show({
															title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
															msg: json.error,
															buttons: Ext.Msg.OK,
															icon: Ext.MessageBox.ERROR
														});
													} else if(json.message) {
														Ext.Msg.show({
															title:'<?=$this->db->escape_str($this->lang->line("THE_FOLLOWING_EVENT_HAPPENED"))?>',
															msg: json.message,
															buttons: Ext.Msg.OK,
															icon: Ext.MessageBox.INFO,
														});
														winUser.close();
													}
												}
											});
										}
										} }
								<? } else { ?>
									
								<? } ?>
							<? } ?>
						],
						stripeRows: true,
						autoExpandColumn: 'insName',
						autoHeight: true,
						autoWidth: true,
						border: false,
						frame: false

					});
					
					
					//grid<?=$this->input->post("usrId")?>.render('innerGrid<?=$this->input->post("usrId")?>');
					<? if($strHelp) { ?>
						new Ext.Panel({
							layout: '',
							border: false,
							frame: true,
							collapsible:  false,
							renderTo: 'frmUserPrivileges',
							html: '<?=$this->db->escape_str($strHelp)?>',
							padding: 5,
							style: {margin: '3px'}
						});
					<? } ?>
					grid<?=$this->input->post("usrId")?>.render('frmUserPrivileges');
					<?
				}
			} else { ?>
				new Ext.Panel({
					layout: '',
					border: false,
					frame: true,
					collapsible:  false,
					renderTo: 'frmUserPrivileges',
					html: '<?=$this->db->escape_str($this->lang->line("PRIVILEGES_DOESNT_EXISTS"))?>',
					padding: 5,
					style: {margin: '3px'}
				});
			<? }
		}
	}
	
	function usr2ent_insert_update() {
		if(intval($this->input->post("usrId")) == $this->session->userdata("usrId")) {
			echo json_encode(array("error" => $this->lang->line("YOU_CANNOT_EDIT_YOUR_OWN_PRIVILEGES")));
			return;
		}
		$this->load->model("user");
		$this->load->model("usr2ent");
		if($this->user->getUser("usr_id = '".intval($this->input->post("usrId"))."'")) {
			$getUsr2ent = $this->usr2ent->getUsr2ent($where = "u2e_usr_id = '".$this->db->escape_str($this->input->post("usrId"))."'");
			if(isset($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")]) and $this->input->post("checked") == 0) {
				$this->usr2ent->delete($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")]);
			} elseif(!isset($getUsr2ent["PAGE_CAT_".$this->input->post("ENTITY")]["u2eIds"][$this->input->post("insId")])) {
				$this->usr2ent->insert(array(
					"u2e_usr_id" => $this->input->post("usrId"),
					"u2e_ins_id" => $this->input->post("insId"),
					"u2e_page_cat" => $this->input->post("ENTITY"),
				));
			}
		}
	}

	function attach_institute() {
		$this->load->model("ent2image");
		$this->ent2image->update($this->input->post("e2i_id"), array(
			"e2i_main_slider_2_ins_id" => $this->input->post("e2i_main_slider_2_ins_id") ? $this->input->post("e2i_main_slider_2_ins_id") : NULL,
		));
	}
	
}